Merge 2 collections and change a property of same objects

910 views Asked by At

I have 2 collections of customers:

  1. all customers list
  2. related customer list

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?

1

There are 1 answers

2
Robert McKee On BEST ANSWER

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()});