[英]Actual difference between two lists - not Except
Let's say I have the list 假设我有清单
var L1 = new List<int>{1,1,2};
var L2 = new List<int>{1};
If I do 如果我做
L1.Except(L2)
I get List<int>{2}
- Fair enough. 我得到
List<int>{2}
-足够公平。
But is there shorthand to do something like L1.Minus(L2)
where I would get List<int>{1,2}
但是是否有速记来执行类似
L1.Minus(L2)
,我将得到List<int>{1,2}
Basically only remove items as many times as it finds them in L2. 基本上只删除在L2中找到它们的次数。
I could write this out - hoping I don't have to. 我可以写出来-希望我不必这样做。
If you were to write it yourself, it could look like this: 如果您要自己编写,则可能看起来像这样:
public static class ExtensionMethods
{
static public IEnumerable<T> Minus<T>(this IEnumerable<T> input, IEnumerable<T> removal)
{
var result = input.ToList();
foreach (var r in removal) result.Remove(r);
return result;
}
}
Or possibly like this if you aren't so worried about readability: 如果您不太担心可读性,也可以这样:
public static class ExtensionMethods
{
static public IEnumerable<T> Minus<T>(this IEnumerable<T> input, IEnumerable<T> removal)
{
var remaining = removal.ToList();
return input.Where
(
a => !remaining.Remove(a)
);
}
}
Example usage: 用法示例:
public class Program
{
public static void Main()
{
var L1 = new List<int>{1,1,2};
var L2 = new List<int>{1};
var L3 = L1.Minus(L2);
foreach (var l in L3)
{
Console.WriteLine(l);
}
}
}
Output: 输出:
1
2
使用ForEach和lambda表达式的最小示例:
L2.ForEach(x => L1.Remove(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.