Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Objects with int property compared to List of Int

Tags:

c#

.net

list

I have 2 lists. First is a list of objects that has an int property ID. The other is a list of ints.

I need to compare these 2 lists and copy the objects to a new list with only the objects that matches between the two lists based on ID. Right now I am 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);
}

This seems like it is going to be very slow as it is iterating over each list many times. Is there way to do this without using 2 foreach loops like this?

like image 991
mameesh Avatar asked Jan 07 '23 11:01

mameesh


2 Answers

One slow but clear way would be

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

You can make this quicker by turning the intList into a dictionary and using ContainsKey instead.

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

Even better still, a HashSet:

var intHash = new HashSet(intList);
var matched = cars.Where(car => intHash.Contains(car.id)).ToList();
like image 120
Jamiec Avatar answered Jan 16 '23 19:01

Jamiec


You could try some simple linq something like this should work:

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

this will take your list of cars and then find only those items where the id is contained in your intList.

like image 28
David Shorthose Avatar answered Jan 16 '23 19:01

David Shorthose