[英]Remove items from list 1 not in list 2
我正在學習編寫lambda表達式 ,我需要有關如何從列表中刪除不在另一個列表中的所有元素的幫助。
var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };
// Remove all list items not in List2
// new List Should contain {4,5}
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
您可以使用Contains通過RemoveAll執行此操作:
list.RemoveAll( item => !list2.Contains(item));
或者,如果您只想要交集,使用Enumerable.Intersect會更有效:
list = list.Intersect(list2).ToList();
不同的是,在后一種情況下,您將不會獲得重復的條目。 例如,如果list2
包含2,則在第一種情況下,您將獲得{2,2,4,5}
,在第二種情況下,您將獲得{2,4,5}
。
對象的解決方案 (可能比horaces解決方案更容易):
如果您的列表包含對象而不是標量,那么通過刪除對象的一個選定屬性就可以了:
var a = allActivePatientContracts.RemoveAll(x => !allPatients.Select(y => y.Id).Contains(x.PatientId));
這個問題已被標記為已回答,但有一個問題。 如果列表包含對象而不是標量,則需要做更多的工作。
我一遍又一遍地嘗試使用Remove()和RemoveAt()以及各種各樣的東西,但沒有一個能正常工作。 我甚至無法讓Contains()正常工作。 從來沒有匹配過。 我很難過,直到我懷疑它可能無法正確匹配項目。
當我意識到這一點時,我重構了item類來實現IEquatable,然后它開始工作了。
這是我的解決方案:
class GenericLookupE : IEquatable<GenericLookupE>
{
public string ID { get; set; }
public bool Equals( GenericLookupE other )
{
if ( this.ID == other.ID ) return true;
return false;
}
}
在我這樣做之后,Reed Copsey的上述RemoveAll()回答對我來說非常合適。
請參閱: http : //msdn.microsoft.com/en-us/library/bhkz42b3.aspx
list = list.Except(list2).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.