Reputation: 12885
I have 2 collections of customers:
All customers list has all the customers. Related customers list contains some customers from the "all customers list"
I want to return a 3rd collection called mergedCustomers where I can execute a function/logic to create a new class "MergeCustomer" where the Id of each collections elements are equal and for those I set on the new mergeCustomer a property IsSelected = true.
My 3rd collection must of course return all customers, I just want that the IsSelected property is changed where all customers match with related customer collection.
What is the linq function to do this?
Upvotes: 0
Views: 904
Reputation: 21477
The easy way:
var mergedCustomers=customers.Select(c=>new MergedCustomer{
Id=c.Id,
IsSelected=relatedCustomers.Select(rc=>rc.Id).Contains(c.Id)
});
The Join way:
var mergedCustomers=customers.Join(relatedCustomers,c=>c.Id,rc=>rc.Id,
(c,g)=> g.Select(rc=>new MergedCustomer { Id=rc.Id,IsSelected=true})
.DefaultIfEmpty(new MergedCustomer {Id=c.Id, IsSelected=false}));
Another way (I think this should work):
var mergedCustomers=customers.Join(relatedCustomers,c=>c.Id,rc=>rc.Id,
(c,g)=> new MergedCustomer { Id=rc.Id,IsSelected=g.Any()});
Upvotes: 1