C# Linq group by 和 group by into 运用实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# Linq group by 和 group by into 运用实例相关的知识,希望对你有一定的参考价值。
Form:在一个查询中如果需要查询多个数据源则使用多个From
Group:分组,将查询结果按照指定分组条件放入到不同的分组中
Into:使用Into上下文关键字创建一个临时标示符,一遍将group、join或select子句的结果存储到新的标示符中
Let:在查询中增加一个范围变量,可以直接运算来的,也可以调用外部方法来存放外部方法得到的结果集;
List<Student> listStudent = new List<Student>
{
new Student{StuNo="11",StuName="李三",ClassNo="1"},
new Student{StuNo="22",StuName="王五",ClassNo="2"},
new Student{StuNo="33",StuName="张猛",ClassNo="3"},
new Student{StuNo="44",StuName="刘刚",ClassNo="1"},
new Student{StuNo="55",StuName="夏飞",ClassNo="2"},
new Student{StuNo="66",StuName="胡凯",ClassNo="3"},
};
List<ClassInfo> listClassInfo = new List<ClassInfo>() {
new ClassInfo{ClassNo="1",ClassName="班级一班"},
new ClassInfo{ClassNo="2",ClassName="班级二班"},
new ClassInfo{ClassNo="3",ClassName="班级三班"},
};
var item = from s in listStudent
group s by s.ClassNo;
listBox1.Items.Clear();
foreach(IGrouping<string ,Student> ig in item)
{
listBox1.Items.Add(ig.Key);
listBox1.Items.Add("=============================");
foreach(Student s in ig)
{
string info = string.Format("学号:{0} 姓名:{1} 班级:{2} 当前分组:{3}", s.StuNo, s.StuName, s.ClassNo,ig.Key);
listBox1.Items.Add(info);
}
}
========================================
List<Student> listStudent = new List<Student>
{
new Student{StuNo="11",StuName="李三",ClassNo="1"},
new Student{StuNo="22",StuName="王五",ClassNo="2"},
new Student{StuNo="33",StuName="张猛",ClassNo="3"},
new Student{StuNo="44",StuName="刘刚",ClassNo="1"},
new Student{StuNo="55",StuName="夏飞",ClassNo="2"},
new Student{StuNo="66",StuName="胡凯",ClassNo="3"},
};
List<ClassInfo> listClassInfo = new List<ClassInfo>() {
new ClassInfo{ClassNo="1",ClassName="班级一班"},
new ClassInfo{ClassNo="2",ClassName="班级二班"},
new ClassInfo{ClassNo="3",ClassName="班级三班"},
};
var query_stu = from stu in listStudent
group stu by stu.ClassNo into c_table
from cl in listClassInfo
where cl.ClassNo == c_table.Key
select new { classId = c_table.Key, className = cl.ClassName,stus = c_table };
foreach(var item in query_stu)
{
listBox1.Items.Add("=====================" + item.className + "=================");
foreach(Student s in item.stus)
{
string info = string.Format("学号:{0} 姓名:{1} ", s.StuNo, s.StuName);
listBox1.Items.Add(info);
}
以上是关于C# Linq group by 和 group by into 运用实例的主要内容,如果未能解决你的问题,请参考以下文章
.NET(C#) System.Linq中实现多列group by(分组)的示例代码
c# Linq select join on select group by