简体   繁体   English

应用分组依据,然后全选

[英]Apply Group by and then select all

I have a list which has following items : 我有一个包含以下项目的列表:

Id ID
Name 名称
Currency 货币
Fund 基金

I am applying group by on this list as follows : 我在此列表上按分组方式进行申请,如下所示:

var testData = from fl in fundsList
                           group fl by new { fl.Name } into groupedData
                           select new
                           {
                               groupedData.Key.Name,
                           };  

But this gives me only Name in the selected data. 但这在选择的数据中仅给我名称 What I want is apply group by on basis of Name and get all items ie Id, Name, Currency and Fund in select . 我想要的是基于名称申请分组,并选择中获得所有项目,即ID,名称,货币和资金 I tried accessing others in select, but they don't come with Key. 我尝试选择访问其他人,但他们没有Key。

Try this: 尝试这个:

var testData = fundsList.GroupBy(fl => fl.Name);

Now you will get an IEnumerable<IGrouping<T>> , which containes many key => valueCollection items. 现在,您将获得IEnumerable<IGrouping<T>> ,其中包含许多key => valueCollection项目。

var testData = from fl in fundsList
                           group fl by new { fl.Name } into groupedData
                           select new
                           {
                              GroupName=  groupedData.Key.Name,
                              Items = grp.ToList()
                           };  

groupedData within your query implements IEnumerable<YourEntity> with items that belongs to that group, so you can easily do following: groupedData您的查询中实现IEnumerable<YourEntity>同属于该组物品,所以你可以很容易做到以下几点:

var testData = from fl in fundsList
                           group fl by fl.Name into groupedData
                           select new
                           {
                              Name = groupedData.Key.Name,
                              Items = grp.ToList()
                           };  

Or in method based query: 或在基于方法的查询中:

var testData = fundsList.GroupBy(fl => fl.Name)
                        .Select(g => new { Name = g.Key, Items = g.ToList() });

Every item withint testData collection will have two properties: testData集合中的每个项目都将具有两个属性:

  • Name with group name Name与组名
  • Items with all items that belongs to the group Items与属于该组的所有项目

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

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