我有两个列表:
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/