- Home /
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 Lists.
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
It depends if you test occurs often or not. If not, I think that two "for" loops are good enough. If you launch this test at every frame and the lists are quite long, you may think of using a hash table.
Thanks for the reply $$anonymous$$iraSensei, I am not calling it too often and decided to use Linq given it's powerful (albeit slightly slower) features. I posted an example below.
Answer by Overcast · May 21, 2013 at 01:10 PM
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...
}
Answer by abhinandand · Nov 28, 2017 at 06:30 AM
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
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to check if a value exists in an array (C#) 3 Answers
Dictionary, List, Hashtable - Best Practices 1 Answer
Make Lists within a List 0 Answers