Group by key and send values into list using LINQ
c#, linq
Solution
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 `NodeIds` in the `Address` are unique; if they are not, add `Distinct()` after `SelectMany`.
Problem
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: ``` 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 ``` List<Address> listOfFilteredAddresses = listOfAddresses.GroupBy(x=>x.AddressId).Select(y=>new Address{AddressId=y.Key, NodeIds=?}); ``` Thanks in advance..