Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query for selecting from one list based on another

public class Test
{
  int i;
  string s;
}

List<Test> testList = new List<Test>(); //assume there are some values in it.

List<int> intList = new List<int>(){ 1,2,3};

How to I say get items from testList where i is in intList using the linq to objects.

something like List<Test> testIntList = testList.Where(t=>t.i in intList)

like image 215
Alex J Avatar asked Sep 16 '11 21:09

Alex J


2 Answers

Technically, it would be:

List<Test> testIntList = testList.Where(t => intList.Contains(t.i)).ToList();

However, that might be slow if intList is large, since List<T>.Contains performs its search in O(n). A faster approach would be to use a HashSet<T>:

HashSet<int> intList = new HashSet<int>(){ 1,2,3 };
like image 154
Etienne de Martel Avatar answered Oct 22 '22 22:10

Etienne de Martel


This would also be interesting and would perform well:

List<test> finalList = testList.Join(intList, 
                                     test => test.id,
                                     i => i,
                                     (t, i) => t).ToList();

You know when you join tables in a SQL SELECT? This is how to do it using Linq to Objects.

like image 37
Adriano Carneiro Avatar answered Oct 22 '22 20:10

Adriano Carneiro