List of objects with int property compared to List of Int

I have 2 lists. The first is a list of objects with an int property identifier. Another is a list of ints.

I need to compare these 2 lists and copy the objects to the new list only with objects that correspond to two lists based on ID. I am currently using 2 foreach loops as follows:

var matched = new list<Cars>();
foreach(var car in cars)
foreach(var i in intList)
{
 if (car.id == i) 
  matched.Add(car);
}

It seems to be very slow as it repeats each list multiple times. Is there a way to do this without using two foreach loops like this?

+4
source share
2 answers

One slow but understandable way is

var matched = cars.Where(car => intList.Contains(car.id)).ToList();

You can do this faster by including intListin the dictionary and using ContainsKey.

var intLookup = intList.ToDictionary(k => k);
var matched = cars.Where(car => intLookup.ContainsKey(car.id)).ToList();

, HashSet:

var intHash = new HashSet(intList);
var matched = cars.Where(car => intHash.Contains(car.id)).ToList();
+8

linq - :

var matched = cars.Where(w => intList.Contains(w.id)).ToList(); 

, , intList.

+1

Source: https://habr.com/ru/post/1609345/


All Articles