Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ I have a list of lists, how do I select all objects that exist in every list? [duplicate]

Tags:

c#

linq

I have a list of lists:

List<Tuple<string, List<SomeObject>>

I want to select all SomeObjects that exist in all rows of the list above.

Some will just exist in one or two lists, but I want all objects that exist in every single list, with other objects discarded.

I can't figure out an elegant solution to this without a bunch of c# code. Is there a nice way?

like image 674
NibblyPig Avatar asked Dec 02 '25 03:12

NibblyPig


1 Answers

list.Select (x => x.Item2 as IEnumerable<SomeObject>)
    .Aggregate((x,y)=> x.Intersect(y))
    .ToList();

Or, as Jeppe Stig Nielsen suggested (and I think it's much more elegant):

list.Select(x => x.Item2.AsEnumerable())
    .Aggregate(Enumerable.Intersect)
    .ToList();
like image 116
Juan Lopes Avatar answered Dec 05 '25 01:12

Juan Lopes



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!