Fastest, cleanest way to find common items in 2 lists

Hi Everyone,

This is a bit of a general programming question sorry. I am just learning C#, and was wondering if someone could help me with getting my head around the most efficient method for handling this with List<>s.

I have a list, and I want to compare it to another list and execute some further instruction if both lists have exactly 2 items in common.

I know simple brute ways to do it, but I belief there are some list functions for this sort of thing, and I am trying to expand my capability with C#, rather than relying on old habits.

Thanks for your time

1 Like

OK, I found an answer, for anyone else interested, I decided to use LINQ. To do so:

Make sure you add it to your script:

using System.Linq

Then use:

IEnumerable both = list1.Intersect(list2);
if(both.Count() == 2){
    //do...
}

It is recommended not to use Linq in unity scripting to avoid garbage in the game,It is recommended not to use Linq in Unity scripting to avoid unwanted garbage in the game