using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<StudentDemo> student_list = GetStudentList();
List<ClassDemo> class_list = GetClassList();
//通过班级分组获取班级下面的学生个数
var res = from c in class_list
join s in student_list on c.class_id equals s.class_id
into groups //分组
orderby groups.Count() descending // 这个可以获得数量
select new ClassNew
{
class_id = c.class_id,
class_name = c.class_name,
student_count = groups.Count()
};
}
private static List<ClassDemo> GetClassList()
{
List<ClassDemo> list = new List<ClassDemo>();
list.Add(new ClassDemo
{
class_id = 1,
class_name = "班级1"
});
list.Add(new ClassDemo
{
class_id = 2,
class_name = "班级2"
});
list.Add(new ClassDemo
{
class_id = 3,
class_name = "班级3"
});
return list;
}
private static List<StudentDemo> GetStudentList()
{
List<StudentDemo> list = new List<StudentDemo>();
list.Add(new StudentDemo
{
student_id = 1,
student_name = "学生1",
class_id = 1
});
list.Add(new StudentDemo
{
student_id = 2,
student_name = "学生2",
class_id = 1
});
list.Add(new StudentDemo
{
student_id = 3,
student_name = "学生3",
class_id = 1
});
list.Add(new StudentDemo
{
student_id = 4,
student_name = "学生4",
class_id = 2
});
list.Add(new StudentDemo
{
student_id = 5,
student_name = "学生5",
class_id = 2
});
return list;
}
}
public class StudentDemo
{
public int student_id { get; set; }
public string student_name { get; set; }
public int class_id { get; set; }
}
public class ClassDemo
{
public int class_id { get; set; }
public string class_name { get; set; }
}
public class ClassNew : ClassDemo
{
public int student_count { get; set; }
}
}
C# Linq 分组查询 into groups
最新推荐文章于 2024-07-30 15:40:41 发布