【问题标题】:c# Remove items in a custom list, based on another List<int>c# 根据另一个 List<int> 删除自定义列表中的项目
【发布时间】:2018-05-23 12:28:21
【问题描述】:

我有一个自定义列表 List。它返回所有项目。 Info的结构如下:

public class Info
  {
    public string Code { get; set; }
    public string ClinicianDescription { get; set; }
  }

我想从列表中排除任何 Info 对象,其中 Code 属性等于单独列表中的任何值。

在一个干净的方法之后,我尝试使用 .Except(),但我必须将列表转换为同一个对象,这似乎不正确。

到目前为止,我已经尝试过这样的事情:

List<int> ids = contactList;
var List<Info> test = info.RemoveAll(x => ids.Any(i => i == x.Code));

【问题讨论】:

  • 为什么不使用循环?您是在寻找干净的方式还是困难的方式
  • var List&lt;Info&gt; test ... 会导致编译错误

标签: c# list


【解决方案1】:

您可以使用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 Codeids 中的整数进行比较。在这里,因为我们在同一个源集合上使用.Except,所以元素的比较将按预期进行,即使它依赖于默认引用相等(因为它在两个IEnumerables 中都是相同的元素引用)。

  • RemoveAll 返回一个表示从列表中修剪的元素数量的 int - 结果不能分配给另一个 List

【讨论】:

  • 这不起作用,因为iint。需要解析一个或在另一个上调用 ToString()。
【解决方案2】:

您也可以使用这种方法:

 List<Info> info = new List<Info>();
 //fill info with objects

 List<string> excludeCodes = new List<string>();
 //fill excludeCodes with values

 var result = info.Where(i => !excludeCodes.Contains(i.Code)).ToList();

【讨论】:

    【解决方案3】:

    为什么不能用Contains()like

    List<Info> test = info
                         .Where(i => !ids.Contains(i.Code)).ToList();
    

    【讨论】:

      【解决方案4】:

      您尝试将字符串与 int 进行比较!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-06
        • 2016-11-06
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        • 2020-03-17
        • 2019-06-23
        • 2011-02-14
        相关资源
        最近更新 更多