【问题标题】:Remove overlapping items between two List<string> collections删除两个 List<string> 集合之间的重叠项
【发布时间】:2010-10-20 22:01:26
【问题描述】:

我有两个List集合,我们称它们为allFieldNames(完整集)和excludedFieldNames(部分集)。我需要派生第三个列表,它给我所有非排除的字段名称。换句话说,在excludedFieldNames 中没有找到allFieldNames 的子集列表。这是我当前的代码:

public List<string> ListFieldNames(List<string> allFieldNames, List<string> excludedFieldNames)
        {
            try
            {
                List<string> lst = new List<string>();

                foreach (string s in allFieldNames)
                {
                    if (!excludedFieldNames.Contains(s)) lst.Add(s);
                }
                return lst;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

我知道必须有比手动迭代更有效的方法。请提出建议。

【问题讨论】:

    标签: linq collections


    【解决方案1】:

    您可以使用Except 方法:

    return allFieldNames.Except(excludedFieldNames).ToList();
    

    (如果您愿意返回 IEnumerable&lt;string&gt; 而不是 List&lt;string&gt;,那么您也可以省略最后的 ToList 调用。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      相关资源
      最近更新 更多