首页 > 数据库 >C#基础:数据库中使用Linq作分组处理(反射/直接分组)

C#基础:数据库中使用Linq作分组处理(反射/直接分组)

时间:2024-08-19 19:24:08浏览次数:8  
标签:group C# List Linq 分组 var new public

目录

一、使用反射分组

二、不使用反射分组

三、调用示例

四、代码demo

一、使用反射分组
private static List<GroupList<T>> GetGroupList<T>(List<T> entities, string groupByProperty)
{
    // 获取分组字段的类型
    var propertyInfo = typeof(T).GetProperty(groupByProperty);
    if (propertyInfo == null)
    {
        throw new ArgumentException($"类型 {typeof(T).Name} 不包含名为 {groupByProperty} 的属性.");
    }

    // 按指定属性分组
    var groupedEntities = entities.GroupBy(e => propertyInfo.GetValue(e, null));

    // 创建分组列表
    List<GroupList<T>> groupLists = new List<GroupList<T>>();

    foreach (var group in groupedEntities)
    {
        GroupList<T> groupList = new GroupList<T>
        {
            GroupKey = group.Key.ToString(), // 使用分组键作为GroupKey
            List = group.ToList(), // 分组数据
            //Count = group.Count() //每组数据条数
        };
        groupLists.Add(groupList);
    }

    return groupLists;
}
二、不使用反射分组
private static List<GroupListStudent> GetGroupListSimple(List<Student> entities)
{
    // 根据班级分组
    var groupedStudents = entities.GroupBy(s => s.ClassNumber);

    // 创建分组列表
    List<GroupListStudent> groupLists = new List<GroupListStudent>();

    foreach (var group in groupedStudents)
    {
        GroupListStudent groupList = new GroupListStudent
        {
            GroupKey = group.Key.ToString(),
            List = group.ToList(),
           // Count = group.Count()
        };
        groupLists.Add(groupList);
    }
    return groupLists;
}
三、调用示例
//反射获取分组
var result = GetGroupList(Students, "ClassNumber");
//直接获取分组
var result2 = GetGroupListSimple(Students);
四、代码demo
using System;
using System.Collections.Generic;
using System.Linq;

namespace StudentClassExample
{
    // 学生类
    public class Student
    {
        public string Name { get; set; }
        public int ClassNumber { get; set; }

        public Student(string name, int classNumber)
        {
            Name = name;
            ClassNumber = classNumber;
        }

    }

    public class GroupList<T>
    {
        public string GroupKey { get; set; }

        public int Count { get => List.Count; }

        public List<T> List { get; set; } = new List<T>();

    }


    public class GroupListStudent
    {
        public string GroupKey { get; set; }

        public int Count { get => List.Count; }

        public List<Student> List { get; set; } = new List<Student>();

    }

    // 主程序
    class Program
    {
        static void Main(string[] args)
        {
            // 创建1班的学生
            List<Student> Students = new List<Student>
            {
                new Student("学生1-1", 1),
                new Student("学生1-2", 1)
            };

            // 创建2班的学生
            List<Student> class2Students = new List<Student>
            {
                new Student("学生2-1", 2),
                new Student("学生2-2", 2),
                new Student("学生2-3", 2)
            };
            Students.AddRange(class2Students);
            //反射获取分组
            var result = GetGroupList(Students, "ClassNumber");
            //直接获取分组
            var result2 = GetGroupListSimple(Students);
            ;
        }

        private static List<GroupList<T>> GetGroupList<T>(List<T> entities, string groupByProperty)
        {
            // 获取分组字段的类型
            var propertyInfo = typeof(T).GetProperty(groupByProperty);
            if (propertyInfo == null)
            {
                throw new ArgumentException($"类型 {typeof(T).Name} 不包含名为 {groupByProperty} 的属性.");
            }

            // 按指定属性分组
            var groupedEntities = entities.GroupBy(e => propertyInfo.GetValue(e, null));

            // 创建分组列表
            List<GroupList<T>> groupLists = new List<GroupList<T>>();

            foreach (var group in groupedEntities)
            {
                GroupList<T> groupList = new GroupList<T>
                {
                    GroupKey = group.Key.ToString(), // 使用分组键作为GroupKey
                    List = group.ToList(), // 分组数据
                    //Count = group.Count() //每组数据条数
                };
                groupLists.Add(groupList);
            }

            return groupLists;
        }


        private static List<GroupListStudent> GetGroupListSimple(List<Student> entities)
        {
            // 根据班级分组
            var groupedStudents = entities.GroupBy(s => s.ClassNumber);

            // 创建分组列表
            List<GroupListStudent> groupLists = new List<GroupListStudent>();

            foreach (var group in groupedStudents)
            {
                GroupListStudent groupList = new GroupListStudent
                {
                    GroupKey = group.Key.ToString(),
                    List = group.ToList(),
                   // Count = group.Count()
                };
                groupLists.Add(groupList);
            }
            return groupLists;
        }
    }
}

标签:group,C#,List,Linq,分组,var,new,public
From: https://blog.csdn.net/m0_67412019/article/details/141332828

相关文章

  • 微分方程(Blanchard Differential Equations 4th)中文版Section3.3
    具有实特征值的线性系统的相图在前面的部分,我们看到直线解在求解某些线性微分方程系统的通解中起着主导作用。为了求解这样的系统,我们首先使用代数方法计算系数矩阵的特征值和特征向量。当我们找到一个实特征值和一个相关的特征向量时,就可以写出对应的直线解。此外,在特定情......
  • 【OCPP】ocpp1.6协议第5.11章节Remote Start Transaction的介绍及翻译
    目录5.11RemoteStartTransaction-概述1.目的2.消息类型2.1RemoteStartTransaction.req2.2RemoteStartTransaction.conf3.流程描述4.状态和值域5.特殊情况5.11远程启动交易RemoteStartTransaction-原文译文5.11RemoteStartTransaction-概述在OCPP......
  • PointNetCFD-main
    #####Point-clouddeeplearningforpredictionoffluidflowfieldsonirregulargeometries(supervisedlearning)######Authors:AliKashefi([email protected])andDavisRempe([email protected])#Description:ImplementationofPointNetfor*super......
  • 错误 1 error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MTd_StaticDebug”
    前言全局说明VisualStudio2013jsoncpp0.10.7库编译LNK2038一、说明环境:Windows7旗舰版VisualStudio2013二、错误内容错误1errorLNK2038:检测到“RuntimeLibrary”的不匹配项:值“MTd_StaticDebug”不匹配值“MDd_DynamicDebug”(mfc_mqtt-client-po......
  • Oracle21c数据库安装问题记录
    Oracle21c数据库安装问题记录1.安装问题1.1Oracle监听器配置错误:为该监听程序提供的信息正由此计算机上的其他软件使用转载链接:https://blog.itpub.net/23557469/viewspace-1117140/在Linux上安装好Oracle10g,配置监听器,却得到:为该监听程序提供的信息正由此计算机上的其......
  • 暑假集训csp提高模拟4
    赛时rank43,T1100,T231,T30,T49T2由于学校机子的O2跑的还没有本地的O1快(太快啦!!!),挂了40ptsT4暴力没有取模和特判,挂了5pts与和[ABC238D]ANDandSUM签到题由于\(x\&y=a\),所以有\(x+y=s\ge2*a\)考虑二进制下的加法,如果有一个\(sth\)满足\(a*2+sth=s\),那么\(sth\&a\)......
  • Centos7使用RPM包安装Oracle21c数据库(XE)
    Centos7使用RPM包安装Oracle21c数据库(XE)官方下载链接21c标准版安装包信息:文件名:LINUX.X64_213000_db_home.zip(64-bit)(3,109,225,519bytes)(sha256sum-c05d5c32a72b9bf84ab6babb49aee99cbb403930406aabe3cf2f94f1d35e0916)21cxe版安装包信息:文件名:oracle-data......
  • ctfshow-web入门-sql注入(web224-web230)文件类型注入、routines存储过程与函数状态、ha
    目录1、web2242、web2253、web2264、web2275、web2286、web2297、web2301、web224登录页面测了下没发现注入点存在robots.txt访问/pwdreset.php  ,是管理员密码重置的页面直接重置密码,这里以123456为例使用admin/123456登录 来到一个文件生成界......
  • 【收藏】Arcgis api4.x renderer根据字段值渲染,唯一值渲染和分级渲染
    1.根据字段值渲染(唯一值渲染)  定义唯一值渲染器中每个唯一值的样式,以根据数据字段的不同值为要素指定不同的符号,从而实现基于分类数据的图形化表示。 constrenderer={type:"unique-value",field:"type",defaultSymbol:{type:"simple-marke......
  • 【OpenCV教程】滤波和边缘检测的过程
    @目录1.均值滤波1.1卷积核形状1.2API1.3效果2.高斯滤波2.1卷积核形状2.2API2.3效果3.中值滤波3.1原理3.2API3.3效果4.高斯双边滤波4.1原理4.2API4.3效果5.获取用来形态学操作的滤波器6.腐蚀和膨胀(对二值图)6.1原理6.2腐蚀API6.3效果6.4膨胀API6.5效果7.形态学操作......