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..
GroupBy & ToLookup return a collection that has a key and an inner collection based on a key field value. The execution of GroupBy is deferred whereas that of ToLookup is immediate. A LINQ query syntax can be end with the GroupBy or Select clause.
Advantages of LINQStandardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time. IntelliSense Support: LINQ provides IntelliSense for generic collections.
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
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
.
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()
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With