简体   繁体   English

如何在LINQ查询中使用分组依据?

[英]How to use Group By in LINQ query?

There is linq query in my existing project, something like this: 我现有的项目中有linq查询,如下所示:

group new {a.name,a,description,a.number,i.productname}
by new {i.productname} into grpProduct

There is a Group By in my query and its syntax is like above query. 我的查询中有一个“分组依据”,其语法类似于上述查询。 Means it's using group new and after that by new . 意味着它的使用group new ,之后by new But I am not getting the purpose of this syntax. 但是我没有得到这种语法的目的。 Can anyone help me out on this? 有人可以帮我吗?

Let's say you had a class like this: 假设您有一个这样的课程:

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

And you defined a list and added some students to it... 然后您定义了一个列表,并向其中添加了一些学生...

var students = new List<Student>();

And then you created groups from it like this: 然后您从中创建组,如下所示:

var i = (from s in students
         group new { s.Id, s.Name }
         by new { s.Age });

The by new section specifies the key(s) by which you'd like to create the grouping. by new部分指定您要用来创建分组的键。 So when you execute the query, you'll get one group per Age , and Age will be the "key" for each group. 因此,当您执行查询时,每个Age会得到一个组, Age将成为每个组的“关键”。

(Since there's only one field specified, you could rewrite that part as by s.Age .) (由于仅指定了一个字段,因此可以 by s.Age 重写该部分 。)

The group new section specifies what you'd like to have available in each "group". group new部分指定了您希望在每个“组”中使用的内容。 Whereas Age will be the key, when you drill down into each group you'll have a collection of an anonymous type that includes Id and Name . Age是关键,而当您深入每个组时,您将获得一个匿名类型的集合,其中包括IdName

The by statement declares what will be the key value used to group your data, while the group statement selects what will be "grouped". by语句声明将用于分组数据的键值,而group语句选择将被“分组”的键值。 So your result is going to be a IGrouping on i.productname (it will be the key) and if you fetch each a these grouped items you will access to all the new {a.name,a,description,a.number,i.productname} objects with i.productname corresponding to this key. 因此,您的结果将是在i.productname上进行IGrouping (这将是关键),如果您分别获取这些分组的项目,则可以访问所有new {a.name,a,description,a.number,i.productname} i.productname new {a.name,a,description,a.number,i.productname}对象,其i.productname与此键对应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM