c# - 保留重复项的两个列表之间的区别

标签 c# linq

我有两个列表:

var list1 = new List<string> { "A", "A", "B", "C" };
var list2 = new List<string> { "A", "B" };

我想生成一个列表

var result = new[] { "A", "C" };

其中列表是从 list2 中删除的 list1 中的所有元素我认为没有 Linq 扩展方法,因为 Except 删除重复项。

执行此操作的非 linq 方法是:

var tempList = list1.ToList();
foreach(var item in list2)
{
    tempList.Remove(item);
}

但我想知道是否有我可能错过的 Linq 扩展方法。

编辑:

因为可能没有,所以我做了一个扩展方法。

public static class LinqExtensions
{
    public static IEnumerable<T> RemoveRange<T>(this IEnumerable<T> source, IEnumerable<T> second)
    {
        var tempList = source.ToList();
            
        foreach(var item in second)
        {
            tempList.Remove(item);
        }
        
        return tempList;
    }
    
    public static IEnumerable<TFirst> RemoveMany<TFirst, TSecond>(this IEnumerable<TFirst> source, IEnumerable<TSecond> second, Func<TSecond, IEnumerable<TFirst>> selector)
    {
        var tempList = source.ToList();
            
        foreach(var item in second.SelectMany(selector))
        {
            tempList.Remove(item);
        }
        
        return tempList;
    }
}

用法:

list1.RemoveRange(list2)

最佳答案

看看你的例子,我认为你的意思是“从 list1 中删除了 list2 中的所有元素”:

var lookup2 = list2.ToLookup(str => str);

var result = from str in list1
             group str by str into strGroup
             let missingCount 
                  = Math.Max(0, strGroup.Count() - lookup2[strGroup.Key].Count())
             from missingStr in strGroup.Take(missingCount)
             select missingStr;

关于c# - 保留重复项的两个列表之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801655/

相关文章:

c# - 并行运行多个任务

C# 返回具有祖先和自身但没有其他子元素的 XML 元素

c# - linq2sql 如何跟踪数据库对象?

c# - asp.net 与 c#

c# - 如何在C#中使用反射获取方法的所有属性和属性数据

C# 从 Windows Azure 存储下载返回空文件,没有任何异常

c# - 是否有 LINQ 查询会给我几个最大值的总和?

.net - 在 F# 中使用 LINQ?

c# - 类似 .Net string.CompareOrdinal 的 Linq 函数

java - 为什么ArrayList创建时元素数组为空,而HashSet创建时表为空?