开发者

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(tabulatedI开发者_Python百科nputErrors);

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.

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}

Alternative:

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.

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. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜