2012-06-27 162 views
4
发送值到列表

说我有一个简单的地址类象下面这样:集团通过密钥,并使用LINQ

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上进行分组,因此结果列表将具有基本上在如下重复的情况下卷起的节点ID:

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=?}); 

在此先感谢..

回答

11

你几乎有:

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

这里假定Address中的NodeIds是唯一的;如果不是,请在SelectMany之后加Distinct()

+0

感谢迅速回应做。这工作:) – santosh212

0

有一个更好的办法:

List<Address> listOfFilteredAddresses = 
listOfAddresses 
.GroupBy(a => a.AddressId) 
.Select(g => new Address 
{ 
    AddressId = g.Key, 
    NodeIds = g.ToList() 
}); 
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() 
           };