Home > Software design >  Collection of unique items with custom comparator
Collection of unique items with custom comparator

Time:01-13

I need collection, similar to std::set, so every element can be inserted only once, but I need to provide my custom comparator to decide whether elements are equal. How can I do that in C#? Seems C# doesn't have set at all?

CodePudding user response:

.NET comes with an unordered set type called HashSet<T>, multiple constructors of which accept a user-supplied IEqualityComparer<T> instance:

var set = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);

set.Add("abc"); // the statement returns `true`
set.Add("def"); // the statement returns `true`
set.Add("abc"); // returns `false`, abc already exists in set

set.Contains("abc"); // returns `true` as expected
set.Contains("ABC"); // also `true`, thanks to our case-insensitive comparer

CodePudding user response:

The object you are looking for is HashSet<T>, which will only add items once.

If you want to implement your own equality comparisons, you can have the class implement IEqualityComparer<T> and provide the logic for equality there.

CodePudding user response:

You want a HashSet with a custom IEqualityComparer<T> instance.

CodePudding user response:

You can use SortedSet<T> which has constructor accepting custom IComparer and does not allow duplicate items:

A SortedSet object maintains a sorted order without affecting performance as elements are inserted and deleted. Duplicate elements are not allowed. Changing the sort values of existing items is not supported and may lead to unexpected behavior.

Or SortedDictionary<TKey,TValue> with custom comparer for keys.

  •  Tags:  
  • Related