![](/img/trans.png)
[英]Removing from collection based on values from another collection - Lambda/Linq
[英]Filter collection based on values in another collection
我有一個int數組和一個包含int ID的對象列表。
如果int數組包含1,2,3等,我只想獲取包含這些ID的對象(那些有1,2,3等的對象)。
怎么可以在.NET 3.5中完成?
謝謝
如果你處理小序列,DaveShaw的答案很好。 如果您的ID數組變大,更高效的方法是將數組加載到HashSet<T>
,然后執行完全相同的查詢,除了使用set。
var hashset = new HashSet<int>(ints);
var matches = objects.Where(obj => hashset.Contains(obj.Id));
對於這個和其他更復雜的場景,您還應該了解Enumerable.Join
,它根據鍵匹配兩個序列並產生所需的結果。
var matches = from obj in objects
join id in ints
on obj.Id equals id
select obj;
// var matches = objects.Join(ints, obj => obj.Id, id => id, (obj, id) => obj);
假設objects
是具有Id
屬性的類的實例列表,您可以這樣做。
var ints = new[] {1, 2, 3, };
var matches = objects.Where(obj => ints.Contains(obj.Id));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.