如果我想根据特定的id过滤对象列表,我可以这样做:
list.Where(r => r.Id == idToCompare);
Run Code Online (Sandbox Code Playgroud)
如果,而不是单个idToCompare,我有一个ID列表进行比较怎么办?
与预定义列表进行比较的语法是什么?就像是:
int[] listofIds = GetListofIds();
list.Where(r => r.Id "in listofIds");
Run Code Online (Sandbox Code Playgroud)
Ala*_*lan 55
如果listOfIds是列表,这将起作用,但是,List.Contains()是线性搜索,因此这不是非常有效.
最好将要查找的ID存储到适合搜索的容器中,例如Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
Run Code Online (Sandbox Code Playgroud)
Ant*_*ram 21
var query = list.Where(r => listofIds.Any(id => id == r.Id));
Run Code Online (Sandbox Code Playgroud)
另一种方法,如果listOfIds数组很大,则非常有用:
HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));
Run Code Online (Sandbox Code Playgroud)
您可以使用Contains()扩展方法:
list.Where(r => listofIds.Contains(r.Id))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97268 次 |
| 最近记录: |