我有这样一个类,
class Test
{
public int ID { get; set; }
public string Name { get; set; }
}
我还有一个 List ids;
我想选择 List 中其 ID 在列表 id 中的所有元素。我目前的解决方案是这样的:
var v = from t in tests where ids.Contains(t.ID) select t;
如果List的数量很大,超过10000条,是否有效?
谢谢
最佳答案
你可以试试这个:
var lookup = ids.ToDictionary(x => x);
var matching = tests.Where(t => lookup.ContainsKey(t.ID));
如果 ids
不包含任何重复值,这将有效。
或者(更快,根据下面的评论):
var lookup = new HashSet<int>(ids);
var matching = tests.Where(t => lookup.Contains(t.ID));
即使有重复的 ID,这也会起作用(同样,请参阅下面的评论)。
关于c# - 选择列表中属性在另一个列表中的元素的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26094849/