简体   繁体   English

从另一个List <>中删除List <>中包含的对象?

[英]Removing objects contained in a List<> from another List<>?

I have an object which is contained within a List<>, I need to remove these from another List<> 我有一个包含在List <>中的对象,我需要从另一个List <>中删除它们

eg 例如

List<MyObject> AllElements = new List<MyObject>();
List<MyObject> SearchResults = new List<MyObject>();

... Do something so that SearchResults contains a subset of the objects contained within AllResults ...执行某些操作,以便SearchResults包含AllResults中包含的对象的子集

Currently I do this to delete them from the main list: 目前我这样做是为了从主列表中删除它们:

for(int i = 0; i < SearchResults.Count; i++) 
    AllElements.Remove(SearchResults[i]); 

Is there an nicer [linqier!] way? 有没有更好的[linqier!]方式?

You can use the Enumerable.Except Method (from MSDN) 您可以使用Enumerable.Except方法 (来自MSDN)

List <MyObject> FilteredElements = AllElements.Except(SearchResults).ToList(); List <MyObject> FilteredElements = AllElements.Except(SearchResults).ToList();

IEnumerable<T>.Except你的朋友(如果我正确地阅读你的例子):

allElements = allElements.Except(searchResults);

The following will give you a 'list' where everything in SearchResults was removed. 以下内容将为您提供一个“列表”,其中删除了SearchResults中的所有内容。

var results = AllElements.Where(i => !SearchResults.Contains(i));

You could then do: 然后你可以这样做:

AllElements = results.AsList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM