C# 从另一个中减去一个通用列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18895751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract a generic list from another
提问by Bobby
I am trying remove a list of firmIDs from one list from another. I don't really understand linq but I am pretty sure I need to use it.
我正在尝试从另一个列表中删除一个公司 ID 列表。我不太了解 linq,但我很确定我需要使用它。
List<Firm> firms = GetBusinessDevelopmentFirms(database);
List<Firm> trackedFirms = GetAllCLIFirmsBeingTrackedByUser();
var result = firms.Contains(i => trackedFirms.Contains(i.FirmID));
The last line doesn't work and the system says "unknown method Contains(?)" even though I have put "using System.Linq;" At the top of the class.
最后一行不起作用,即使我已经输入了“使用 System.Linq;”,系统也会说“未知方法包含(?)” 在班级的顶端。
My idea was to remove a list of tracked firms from a list of all firms to find the untracked firms.
我的想法是从所有公司的列表中删除已跟踪公司的列表,以找到未跟踪的公司。
I hope this makes sense.
我希望这是有道理的。
采纳答案by Alireza
var result = firms.Except(trackedFirms); // returns all the firms except those in trackedFirms
回答by Eli Gassert
Contains
is the native method of List<T>
that expects you to pass in a T
. You want Where
instead.
Contains
是List<T>
期望您传入T
. 你想要Where
。
var result = firms.Where(i => trackedFirms.Contains(i.FirmID));
If you expect result
to be a List<T>
then add .ToList()
to the end of your Where
LINQ expression.
如果您希望result
成为一个List<T>
然后添加.ToList()
到您的Where
LINQ 表达式的末尾。
回答by Steven Wood
If you have list X and a list Y, and you want to remove all items in Y that are in X you can experiment with the following:
如果您有列表 X 和列表 Y,并且您想删除 Y 中 X 中的所有项目,您可以尝试以下操作:
X.Intersect(Y)
X.相交(Y)
Comparing two Lists and returning the distinct values and the differences
回答by Alessandro D'Andria
I think this should works
我认为这应该有效
var result = firms.Where(x => !trackedFirms.Any(y => x.FirmID == y.FirmID));
From all the firm in firms
select the firm that isn'tin the trackedFirms
(at least this is what i understand from your question).
从各公司firms
选择的公司,是不是在trackedFirms
(至少这是我从你的问题理解)。
回答by Martin Milan
From your code above, I presume you are trying to get entries from Firms that have a corresponding item in TrackedFirms.
根据您上面的代码,我假设您正试图从在 TrackedFirms 中具有相应项目的公司获取条目。
List<Firm> results = Firms.Where(f => TrackedFirms.Any(t => t.FirmId == f.FirmId)).ToList();
If on the other hand you want untracked firms, then it's :
另一方面,如果您想要未跟踪的公司,那么它是:
List<Firm> results = Firms.Where(f => !TrackedFirms.Any(t => t.FirmId == f.FirmId)).ToList();
回答by Mehmet Taha Meral
The best approach would be Except()
for you case. However, if the List object is different then other one, you can use All()
最好的方法是Except()
你的情况。但是,如果 List 对象与其他对象不同,则可以使用All()
firms.Where(x=> trackedFirms.All(y => y.FirmId != x.FirmId)