Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq union question

Tags:

c#

linq

union

Could someone explain how does Union in LINQ work?

It is told that it merges two sequences and removes duplicates.

But can I somehow customize the duplicate removal behavior - let's say if I wish to use the element from the second sequence in case of duplicate or from the first sequence.

Or even if I wish to somehow combine those values in the resulting sequence?

How should that be implemented?


Update

I guess I described the problem incorrectly, let's say we have some value:

class Value {
   String name
   Int whatever;
}

and the comparer used performs a x.name == y.name check.

And let's say that sometimes I know I should take the element from the second sequence, because it's whatever field is newer / better than the whatever field of the first sequence.

Anyway, I would use the sequence1.Union(sequence2) or sequence2.Union(sequence1) variation of the methods.

Thank you

like image 867
Yippie-Ki-Yay Avatar asked Dec 11 '10 23:12

Yippie-Ki-Yay


1 Answers

You can use second.Union(first) instead of first.Union(second). That way, it will keep the items from second rather than the items from first.

like image 79
Thomas Levesque Avatar answered Nov 15 '22 14:11

Thomas Levesque