linq查询从一个列表中选择另一个列表

Ale*_*x J 5 c# linq-to-objects

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};
Run Code Online (Sandbox Code Playgroud)

我怎么说items from testList where i is in intList使用linq到对象.

就像是 List<Test> testIntList = testList.Where(t=>t.i in intList)

Eti*_*tel 7

从技术上讲,它将是:

List<Test> testIntList = testList.Where(t => intList.Contains(t.i)).ToList();
Run Code Online (Sandbox Code Playgroud)

但是,如果intList很大,那可能会很慢,因为List<T>.Contains在O(n)中执行搜索.更快的方法是使用HashSet<T>:

HashSet<int> intList = new HashSet<int>(){ 1,2,3 };
Run Code Online (Sandbox Code Playgroud)