删除两个 List<string> 集合之间的重叠项目

Mar*_*ark 2 linq collections

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

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*keH 5

您可以使用以下Except方法:

return allFieldNames.Except(excludedFieldNames).ToList();
Run Code Online (Sandbox Code Playgroud)

(如果您愿意返回 anIEnumerable<string>而不是 a ,那么您也List<string>可以省略最后的调用。)ToList