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