Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union two collections but only for objects with a matching id

First off apologies if this is a blatant duplicate, I searched for all phrases that might yield a result but struggled to find an answer/construct my search terms coherently.

I have a Collection 1 and a Collection 2 of Object A.

// Object A Structure
Date
Type
Value

Collection 1 covers dates 1st to 2nd for 2 types and Collection 2 covers dates 3rd to 4th for 1 type:

// Collection 1
[0] = 1st, TypeA, 3
[1] = 2nd, TypeA, 3
[2] = 1st, TypeB, 57
[3] = 2nd, TypeB, 57

// Collection 2
[0] = 3rd, TypeB, 57
[1] = 4th, TypeB, 58

My original requirement was to combine these two collections. Not a problem:

var result = collection1.Union(collection2);

However, I now would like to combine both collections but excluding objects from Collection 1 where the Type does not exist in Collection 2:

// Result Collection
[0] = 1st, TypeB, 57
[1] = 2nd, TypeB, 57
[2] = 3rd, TypeB, 57
[3] = 4th, TypeB, 58

I'm sure there's a simple (hopefully linq) one line solution to this but I just can't get my brain into gear to figure out what it is.

The best (two lines) I've got so far is:

// Get distinct Types from Collection 2
var typesToInclude = collection2.GroupBy(c => c.Type).Select(group => group.First().Type);

var result = collection2.Union(collection1.Where(c => typesToInclude.Contains(c.Type)));

But that feels really clunky and not optimal :(

like image 216
thudbutt Avatar asked Dec 07 '25 02:12

thudbutt


1 Answers

Try the following

var result = collection1
  .Where(x => collection2.Any(c => c.Type == x.Type))
  .Union(collection2);

Essentially first filter collection1 down to the items which have Type values in collection2 and then run the union operation

like image 120
JaredPar Avatar answered Dec 08 '25 14:12

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!