mmmoustache
mmmoustache

Reputation: 2323

Merge two dynamic lists and override values

I have two dynamic lists, with each list item including three properties: 'Id' (int), 'LikesRed' (bool) and 'LikesBlue' (bool).

I would like to merge both lists, grouping each item by it's 'Id', but I would also like to override any 'false' values with any 'true' values.

So for example, here is the data for my two lists:

List1

{ Id = 1, LikesRed = True, LikesBlue = False }
{ Id = 2, LikesRed = True, LikesBlue = False }
{ Id = 4, LikesRed = False, LikesBlue = True }

List2

{ Id = 1, LikesRed = False, LikesBlue = True }
{ Id = 3, LikesRed = False, LikesBlue = True }
{ Id = 4, LikesRed = True, LikesBlue = False }

And here is my intended result:

{ Id = 1, LikesRed = True, LikesBlue = True }
{ Id = 2, LikesRed = True, LikesBlue = False }
{ Id = 3, LikesRed = False, LikesBlue = True }
{ Id = 4, LikesRed = True, LikesBlue = True }

I've managed to merge both lists (but the items are not grouped) using the following:

var results = list1.Concat(list2);

I've also attempted to group the items in this list using LINQ (it works, but I'm not sure what I can/should do with it):

var final = from x in results
            group x by x.Id into g
            select g;

Can anyone offer any advice as to how I can achieve my goal?

Upvotes: 1

Views: 1692

Answers (2)

ckruczek
ckruczek

Reputation: 2410

You can first group the lists by there ids like you already did and dann use Zip to overwrite the values with your preferences.

Upvotes: -1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

Just check if any items in group has value set to true:

from x in list1.Concat(list2)
group x by x.Id into g
select new {
   Id = g.Key,
   LikesRed = g.Any(x => x.LikesRed),
   LikesBlue = g.Any(x => x.LikesBlue)
}

Upvotes: 5

Related Questions