0

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?

Pascal
  • 12,265
  • 25
  • 103
  • 195

1 Answers1

1

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()});
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • The "Another way" is doing a method style join but no equal check is that correct? I always use the join query style. – Pascal Jun 08 '15 at 19:24
  • It is still using the method style join, but since you only care if the group has a match or not, I'm just using `.Any()` to fill the boolean instead of the DefaultIfEmpty type syntax. At that point, c will contain the customer record, g will contain all (if any) relatedCustomer records that match (based on c=>c.Id == rc=>rc.id). This only works in `1:*` type queries, where all you care about is if the `*` exists or not and you aren't pulling ANY data from the `*` side, so it's not common. – Robert McKee Jun 08 '15 at 19:28