-2

I have 3 lists

        List<User> filterRes1 = new List<User>();
        List<User> filterRes2 = new List<User>();
        List<User> filterRes3 = new List<User>();

And I am trying only to get the item that is common on all three of those lists like so.

        decListWithFiltersFinal = filterRes1
            .Intersect(filterRes2)
            .Intersect(filterRes3).ToList();

This does work, but if one list does not contain anything, the result is always nothing.

How can I skip empty lists and still get the comon item between mulitple lists?

Also how can I check if the list is null and not just "empty".

Thank you!

inno
  • 376
  • 2
  • 15
  • 1
    Does this answer your question? [LINQ intersect, multiple lists, some empty](https://stackoverflow.com/questions/3191810/linq-intersect-multiple-lists-some-empty) – IndieGameDev Nov 13 '20 at 13:38

2 Answers2

0
    new [] { filterRes1, filterRes2, filterRes3 }
       .Where(x => x != null && x.Any())
       .Aggregate((IEnumerable<User>)null, (t, l) => t == null ? l : t.Intersect(l))
       .ToList()
Quercus
  • 2,015
  • 1
  • 12
  • 18
  • 1
    Your `Aggregate` can be simplified to `Aggregate((t, l) => t.Intersect(l))`, but then that's pretty much the same as the duplicate answer. – Johnathan Barclay Nov 13 '20 at 15:27
0

So in a pure set mathematics, you are trying to find the intersection of the 3 sets. If one of the sets is blank, then there is no intersection, that is the correct results. So maybe you want to refactor this to consolidate the sets and then look for duplicates ? The duplicates will tell you there was intersections between the sets. It will not tell you where the duplicates came from, but that does not seem to be your problem.

you could use the .AddRange or the .Concat functionality, these will not remove duplicates and will keep the list order.

Do not use Union, because this will remove duplicates.