views:

81

answers:

3

Hi,

As I mentioned in the title I've got 6 List objects in my hand. I want to find the intersection of them except the ones who has no item.

intersectionResultSet =
    list1.
    Intersect(list2).
    Intersect(list3).
    Intersect(list4).
    Intersect(list5).
    Intersect(list6).ToList();

When one of them has no item, normally I get empty set as a result. So I want to exclude the ones that has no item from intersection operation. What's the best way to do that?

Thanks in advance,

+1  A: 

You could use LINQ to get all the list that are longer then 0 , and then send them to the function you've described.

Another option : Override/Extend "Intersect" to a function that does Intersect on a list only if it's not empty , and call it instead of Intersect.

yossale
+6  A: 

You could use something like this:

// Your handful of lists
IEnumerable<IEnumerable<int>> lists = new[]
    {
        new List<int> { 1, 2, 3 }, 
        new List<int>(), 
        null,
        new List<int> { 2, 3, 4 }
    };

List<int> intersection = lists
    .Where(c => c != null && c.Any())
    .Aggregate(Enumerable.Intersect)
    .ToList();

foreach (int value in intersection)
{
    Console.WriteLine(value);
}

This has been tested and produces the following output:

2
3

With thanks to @Matajon for pointing out a cleaner (and more performant) use of Enumerable.Intersect in the Aggregate function.

Daniel Renshaw
Thanks a lot! I'm gonna use this cool piece of code.
anilca
+5  A: 

Simply, using LINQ too.

var lists = new List<IEnumerable<int>>() { list1, list2, list3, list4, list5, list6 };

var result = lists
    .Where(x => x.Any())
    .Aggregate(Enumerable.Intersect)
    .ToList();
Matajon