linq group by子句

时间:2023-03-09 09:10:50
linq group by子句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication5
{
class Program
{
class Person
{
public int Age { set; get; }
public string Name { set; get; }
public Person(int Age,string Name)
{
this.Age = Age;
this.Name = Name;
}
}
static void Main(string[] args)
{
List<Person> PersonList = new List<Person>();
PersonList.Add(new Person(, "limusha")); //通过构造函数构造新对象
PersonList.Add(new Person(, "guojing")); //通过构造函数构造新对象
PersonList.Add(new Person(, "wujunmin")); //通过构造函数构造新对象
PersonList.Add(new Person(, "lupan")); //通过构造函数构造新对象
PersonList.Add(new Person(, "yuwen")); //通过构造函数构造新对象 //PersonList可以看做一张平面表,item是表中的(一)行记录
//下面的linq语句是在表PersonList中按照记录的Age字段进行分组
var query1 = from item in PersonList group item by item.Age;
//使用group子句进行分组
foreach (var element in query1)
{
Console.WriteLine(element.GetType().Name);//得到结果为三个Grouping类型
}
Console.ReadKey();
} }
}

在上边代码运行时

 var query1 = from item in PersonList group item by item.Age;
foreach (var element in query1)
{
Console.WriteLine(element.GetType().Name);//得到结果为三个Grouping类型
}
得到结果为:

linq group by子句

由此得到的是三个Grouping的数据类型,因此element的类型是Gouping,就是记录的分类这样一个类型
按照年龄分成三组,每组记录是Grouping类型 那么要得到具体的数据记录值怎么办呢?
这需要遍历每个分组,得到具体的每条记录(或者具体的字段值)才可以,我们接着对得到的分组数据进行遍历
foreach(var element in query1)//遍历分组数据
{
  foreach(var item in element){//item是分组中的(一)记录,只有取到的是记录才能使用类中的属性名去访问
  Console.WriteLine(
“姓名:”+item.Name+" "+"年龄"+item.Age.toString();
);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication5
{
class Program
{
class Person
{
public int Age { set; get; }
public string Name { set; get; }
public Person(int Age,string Name)
{
this.Age = Age;
this.Name = Name;
}
}
static void Main(string[] args)
{
List<Person> PersonList = new List<Person>();
PersonList.Add(new Person(, "limusha")); //通过构造函数构造新对象
PersonList.Add(new Person(, "guojing")); //通过构造函数构造新对象
PersonList.Add(new Person(, "wujunmin")); //通过构造函数构造新对象
PersonList.Add(new Person(, "lupan")); //通过构造函数构造新对象
PersonList.Add(new Person(, "yuwen")); //通过构造函数构造新对象 //PersonList可以看做一张平面表,item是表中的(一)行记录
//下面的linq语句是在表PersonList中按照记录的Age字段进行分组
var query1 = from item in PersonList group item by item.Age;
//使用group子句进行分组
foreach (var element in query1)
{
Console.WriteLine(element.GetType().Name);//得到结果为三个Grouping类型
foreach (var item in element) {
Console.WriteLine("年龄:"+item.Age+" 姓名: "+item.Name+" item类型为:"+item.GetType().Name);
}
}
Console.ReadKey();
} }
}

执行结果为linq group by子句

可以看到item的类型为Person了