用于从一个基于另一个列表进行选择的Linq查询
本文关键字:行选 列表 选择 查询 Linq 另一个 一个 用于 | 更新日期: 2023-09-27 18:08:55
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};
如何使用对象链接获取items from testList where i is in intList
像List<Test> testIntList = testList.Where(t=>t.i in intList)
技术上来说,应该是:
List<Test> testIntList = testList.Where(t => intList.Contains(t.i)).ToList();
然而,如果intList
很大,这可能很慢,因为List<T>.Contains
在O(n)中执行搜索。更快的方法是使用HashSet<T>
:
HashSet<int> intList = new HashSet<int>(){ 1,2,3 };
这也会很有趣,并且会执行得很好:
List<test> finalList = testList.Join(intList,
test => test.id,
i => i,
(t, i) => t).ToList();
你知道当你在SQL SELECT
中连接表吗?下面是使用Linq to Objects的方法。