C# 使用 LINQ 按键分组并将值发送到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11217792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Group by key and send values into list using LINQ
提问by santosh212
Say I have a simple address class like below:
假设我有一个简单的地址类,如下所示:
public class Address
{
public int AddressId { get; set; }
public List<int> NodeIds { get; set; }
}
and have populated a list of addresses like below:
并填充了如下地址列表:
List<Address> listOfAddresses = new List<Address>
{
new Address {AddressId=1, NodeIds=new List<int>{1}},
new Address {AddressId=2, NodeIds=new List<int>{2}},
new Address {AddressId=3, NodeIds=new List<int>{3}},
new Address {AddressId=1, NodeIds=new List<int>{4}},
new Address {AddressId=1, NodeIds=new List<int>{5}}
}
and I want to group by on AddressIds so the result list will have NodeIds that are essentially rolled up in case of duplicates like below:
我想在 AddressIds 上分组,因此结果列表将包含 NodeIds,这些 NodeIds 基本上会在出现重复的情况下汇总,如下所示:
listOfAddressesWithoutDupes =
AddressId=1, NodeIds=List<int>{1,4,5},
AddressId=2, NodeIds=List<int>{2}},
AddressId=3, NodeIds=new List<int>{3}
so basically I am looking at a groupby function(or something else) that will get me above result
所以基本上我在看一个 groupby 函数(或其他东西),它会让我高于结果
List<Address> listOfFilteredAddresses = listOfAddresses.GroupBy(x=>x.AddressId).Select(y=>new Address{AddressId=y.Key, NodeIds=?});
Thanks in advance..
提前致谢..
采纳答案by dasblinkenlight
You are almost there:
你快到了:
List<Address> listOfFilteredAddresses =
listOfAddresses
.GroupBy(x=>x.AddressId)
.Select(y=>new Address{
AddressId=y.Key
, NodeIds=y.SelectMany(x=>x. NodeIds).ToList()
});
This assumes that NodeIdsin the Addressare unique; if they are not, add Distinct()after SelectMany.
这假设NodeIdsinAddress是唯一的;如果不是,请在Distinct()之后添加SelectMany。
回答by Master Pesho
There is a better way:
有一个更好的方法:
List<Address> listOfFilteredAddresses =
listOfAddresses
.GroupBy(a => a.AddressId)
.Select(g => new Address
{
AddressId = g.Key,
NodeIds = g.ToList()
});
回答by jayanta
You can do by another approach as below
您可以通过以下另一种方法进行
var listOfFilteredAddresses = from e in listOfAddresses
group e by e.AddressId into g
select new
{
AddressID=g.Key,
NodeIDs=g.Select(x=>x.NodeIds).ToList()
};

