我有一个自定义列表List。返回所有项目。 Info的结构如下:
public class Info
{
public string Code { get; set; }
public string ClinicianDescription { get; set; }
}
我想从列表中排除任何 Info 对象,其中 Code 属性等于单独列表中的任何值。
在一个干净的方法之后,我尝试使用 .Except(),但我必须将 List 转换成相同的对象,这似乎不正确。
到目前为止我已经尝试过这样的事情:
List<int> ids = contactList;
var List<Info> test = info.RemoveAll(x => ids.Any(i => i == x.Code));
最佳答案
您可以使用 Except
,尽管这需要一个 IEnumerable
,而不是谓词,并且在确定 equivalence of two objects 时将其与自定义类一起使用时需要小心
var blackListCodes = contactList.Select(i => i.ToString());
var test = info.Except(info.Where(i => blackListCodes.Contains(i.Code)));
但正如 Tomassino 指出的那样,这可以颠倒和简化为:
var test = info.Where(i => !blackListCodes.Contains(i.Code))
请注意,这将投影一个新可枚举,而不是更改现有 info
中的元素,RemoveAll
会这样做。
只是一些其他要点 - 关于您的代码示例:
正如其他人所指出的,
Code
匹配中使用的类型在比较中需要兼容,即您不能将string Code
与ids
中的整数。在这里,因为我们在同一个源集合上使用.Except
,元素的比较将按预期工作,即使它依赖于默认引用相等性(因为它在两个中都是相同的元素引用IEnumerables
).RemoveAll
返回一个表示从列表中删除的元素数量的 int - 结果不能分配给另一个List
。
关于c# 根据另一个 List<int> 删除自定义列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488431/