1

Assume I need to compare multiple sets and find which are equals or not.

In the end, I need to compare multiple sets and create a final set, with unique data taken from each set. Also I need to handle all items which are repeating in different sets.

  • What do you mean by "repeating in different sets"? **(1)** A set may contain duplicates, or **(2)** A set may not contain duplicates, but items may be present in multiple sets. – Matthew Watson Mar 30 '16 at 14:23
  • The "best" collection to use is completely contextual. Sometimes `List` is best, sometimes `HashSet`, sometimes `Dictionary`. Learn the differences between them and decide which is best for this situation. – D Stanley Mar 30 '16 at 14:26

2 Answers2

5

You should use System.Collections.Generic.HashSet<T>

You can create it like:

var hashSet = new HashSet<T>(IEnumerable<T>)

and then use methods to compare:

hashSet.SetEquals(IEnumerable<T> list) - will return true if hashSet and list contains same items

hashSet.Overlaps(IEnumerable<T> list) - will return true if hashSet contains one of the items from list

hashSet.IsSubsetOf(IEnumerable<T> list) - will return true if hashSet is subset of the list (order don't matter)

hashSet.IsProperSubsetOf(IEnumerable<T> list) - same as IsSubsetOf but order matter

hashSet.IsSupersetOf(IEnumerable<T> list) - will return true if hashSet is superset of the list (order don't matter)

hashSet.IsProperSupersetOf(IEnumerable<T> list) - same as IsSupersetOf but order matter

Also there is methods to modify:

hashSet.UnionWith(IEnumerable<T> list) - will modify hashSet to contain elements which are exists in current hashSet or list or in both.

hashSet.symmetricExceptWith(IEnumerable<T> list) - will modify hashSet to contain elements which are only exists in current hashSet or list but not in both.

hashSet.IntersectWith(IEnumerable<T> list) - will modify hashSet to contain elements which are exists in current hashSet and list.

For more information about HashSet see MSDN article.

Sergiy Kozachenko
  • 1,399
  • 11
  • 31
3

You can use the HashSet<T> class, which represents a set of elements with no duplicates, and exposes methods like IntersectWith, UnionWith, ExceptWith etc. for common set operations

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758