8

假设我有一个简单的地址类,如下所示:

public class Address
{
    public int AddressId { get; set; }
    public List<int> NodeIds { get; set; }
}

并填充了如下地址列表:

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}}
}

并且我想按 AddressIds 分组,因此结果列表将包含 NodeIds,如果出现重复,则基本上会汇总如下:

listOfAddressesWithoutDupes = 
AddressId=1, NodeIds=List<int>{1,4,5},
AddressId=2, NodeIds=List<int>{2}},
AddressId=3, NodeIds=new List<int>{3}

所以基本上我正在看一个 groupby 函数(或其他东西),它会让我高于结果

List<Address> listOfFilteredAddresses = listOfAddresses.GroupBy(x=>x.AddressId).Select(y=>new Address{AddressId=y.Key, NodeIds=?});

提前致谢..

4

3 回答 3

15

你快到了:

List<Address> listOfFilteredAddresses =
    listOfAddresses
    .GroupBy(x=>x.AddressId)
    .Select(y=>new Address{
        AddressId=y.Key
    ,   NodeIds=y.SelectMany(x=>x. NodeIds).ToList()
    });

这假设NodeIdsinAddress是唯一的;如果不是,请在Distinct()之后添加SelectMany

于 2012-06-27T00:31:50.017 回答
2

您可以通过以下另一种方法进行

    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()
                                 };
于 2016-06-07T11:05:22.590 回答
1

有一个更好的方法:

List<Address> listOfFilteredAddresses =
listOfAddresses
.GroupBy(a => a.AddressId)
.Select(g => new Address
{
    AddressId = g.Key,
    NodeIds = g.ToList()
});
于 2016-03-23T18:15:16.470 回答