List.except自定义类 [英] List.except on custom class
问题描述
让我说我有一个自定义类:
lets say I have a custom class:
public class WineCellar
{
public string year;
public string wine;
public double nrbottles;
}
让我们说我现在有一个自定义类的列表:
Lets say I now have a List of this custom class:
List<WineCellar> orignialwinecellar = List<WineCellar>();
包含以下项目:
2012 Chianti 12
2011 Chianti 6
2012 Chardonay 12
2011 Chardonay 6
我知道,如果我想比较两个列表并返回一个仅包含不在另一个列表中的项目的新列表,我会这样做:
I know that if I want to compare two list and return a new list that has only items that are not in the other list I would do:
var newlist = list1.Except(list2);
如何将其扩展到自定义类?可以说我有:
How can I extend this to a custom class? Lets say I have:
string[] exceptionwinelist = {"Chardonay", "Riesling"};
我希望将其退回:
List<WineCellar> result = originalwinecellar.wine.Except(exceptionwinelist);
此伪代码显然不起作用,但希望可以说明我要执行的操作.然后,此应返回具有以下项目的自定义类酒窖的列表:
This pseudocode obviously doesnt work but hopefully illustrates what I m trying to do. This shoudl then return a List of the custom class winecellar with following items:
2012 Chianti 12
2012 Chianti 12
2011年基安蒂6
2011 Chianti 6
谢谢.
推荐答案
您真的不想在这里使用Except
,因为您没有WineCellar
对象的集合可以用作黑名单.您所拥有的是一系列规则:我不想要带有这样和那样的葡萄酒名称的对象".
You don't really want to use Except
here, as you don't have a collection of WineCellar
objects to use as a blacklist. What you have is a collection of rules: "I don't want objects with such and such wine names".
因此最好只使用Where
:
List<WineCellar> result = originalwinecellar
.Where(w => !exceptionwinelist.Contains(w.wine))
.ToList();
以易于理解的形式:
我想要所有在例外列表中没有出现葡萄酒名称的WineCellars.
I want all WineCellars where the wine name is not present in the list of exceptions.
顺便说一句,WineCellar
类名有点误导;这些物品不是地窖,而是库存物品.
As an aside, the WineCellar
class name is a bit misleading; those objects are not cellars, they are inventory items.
这篇关于List.except自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!