2012-06-27 69 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() 
           };