Alex J
Alex J

Reputation: 1567

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)

Upvotes: 5

Views: 3573

Answers (2)

Adriano Carneiro
Adriano Carneiro

Reputation: 58665

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.

Upvotes: 2

Etienne de Martel
Etienne de Martel

Reputation: 36995

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 };

Upvotes: 7

Related Questions