[英]Is there a C# equivalent to C++'s std::set_difference?
If so, what is it? 如果是这样,它是什么?
EDIT: In response to comment below: 编辑:回应下面的评论:
var tabulatedOutputErrors = from error in outputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var tabulatedInputErrors = from error in inputErrors
group error by error into errorGroup
select new { error = errorGroup.Key, number = errorGroup.Count() };
var problems = tabulatedOutputErrors.Except(tabulatedInputErrors);
You can expand out the counts if you need to. 如果需要,您可以扩展计数。
LINQ has the Enumerable.Except
extension method, which seems to be what you're looking for. LINQ有
Enumerable.Except
扩展方法,这似乎是你正在寻找的。
Example: 例:
var list1 = new int[] {1, 3, 5, 7, 9};
var list2 = new int[] {1, 1, 5, 5, 5, 9};
var result = list1.Except(list2); // result = {3, 7}
From .NET 3.5 onwards there also exists the HashSet<T>
class (and also the similar SortedSet<T>
class in .NET 4.0. This class (or rather the ISet<T>
interface in .NET 4.0) has an ExceptWith
method which could also do the job. 从.NET 3.5开始,还存在
HashSet<T>
类(以及.NET 4.0中类似的SortedSet<T>
类。这个类(或者更确切地说是.NET 4.0中的ISet<T>
接口)有一个ExceptWith
方法,也可以做这个工作。
Example: 例:
var set1 = new HashSet<int>() {1, 3, 5, 7, 9};
var set2 = new HashSet<int>() {1, 1, 5, 5, 5, 9};
set1.ExceptWith(set2); // set1 = {3, 7}
Of course, it depends on the context/usage whether this approach is more desirable. 当然,这取决于上下文/用法是否更适合这种方法。 The efficiency benefit (doing the difference operation in-place and using hash codes) in most cases is probably negligible.
在大多数情况下,效率优势(就地执行差异操作和使用哈希码)可能是微不足道的。 Either way, take your pick.
无论哪种方式,请选择。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.