Is there a “Set” data structure in .Net?

2019-02-03 21:42发布

Ideally, I'm looking for a templated logical Set class. It would have all of the standard set operations such as Union, Intersection, Etc., and collapse duplicated items.

I ended up creating my own set class based on the C# Dictionary<>- just using the Keys.

6条回答
够拽才男人
2楼-- · 2019-02-03 22:19

Here's a simple implementation:

public sealed class MathSet<T> : HashSet<T>, IEquatable<MathSet<T>>
{
    public override int GetHashCode() => this.Select(elt => elt.GetHashCode()).Sum().GetHashCode();

    public bool Equals(MathSet<T> obj) => SetEquals(obj);

    public override bool Equals(object obj) => Equals(obj as MathSet<T>);

    public static bool operator ==(MathSet<T> a, MathSet<T> b) =>
        ReferenceEquals(a, null) ? ReferenceEquals(b, null) : a.Equals(b);

    public static bool operator !=(MathSet<T> a, MathSet<T> b) => !(a == b);
}

Example usage:

var a = new MathSet<int> { 1, 2, 3 };
var b = new MathSet<int> { 3, 2, 1 };

var c = a.Equals(b);                        // true

var d = new MathSet<MathSet<int>> { a, b }; // contains one element

var e = a == b;                             // true

See this question for why this approach was considered over HashSet.

查看更多
Deceive 欺骗
3楼-- · 2019-02-03 22:26

The best set implementation I have seen is part of the wonderful Wintellect's Power Collections: http://www.codeplex.com/PowerCollections.

The set implementation can be found here:
http://www.codeplex.com/PowerCollections/SourceControl/FileView.aspx?itemId=101886&changeSetId=6259
It has all the expected set operations (union, intersect, etc).

Hope this helps!

查看更多
再贱就再见
4楼-- · 2019-02-03 22:33

Have you checked out the HashSet in 3.5?

查看更多
forever°为你锁心
5楼-- · 2019-02-03 22:34

HashSet<T> is about the closest you'll get, I think.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-03 22:36

No, there is not one natively in the framework. There is an open source implementation that most projects use, (i.e. nHibernate) called Iesi.Collections. Here's a CodeProject article about it:

http://www.codeproject.com/KB/recipes/sets.aspx

查看更多
孤傲高冷的网名
7楼-- · 2019-02-03 22:39

I don't think c# has anything built in, but I know there are a couple of implementations floating around on the net. There are also some good articles around on this sort of thing:

This is part 6 of a series on efficiently representing data structure. This part focuses on representing sets in C#.

An implementation of a set collection
An implementation of a set class
Yet another implementation of a set class

And finally...

I've actually used this library myself as the basis of a set implementation that I did a year or so ago.

查看更多
登录 后发表回答