Ryan A WE
Ryan A WE

Reputation: 59

Key-Value pair Container without the Value

What container should I use to contain a list of values of MyEnum type, but the container must ensure that a value of MyEnum can only can only appear a maximum of once in the entire container, and each element in the container only contains 1 value? If I use Key-Value pair containers the memory allocated for the value part is wasted.

Summed up: Basically, what container is the same as List in C#, but the difference only being that a value is assured to never appear twice in the container?

Upvotes: 2

Views: 372

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460308

I'm fairly sure that you're looking for the HashSet<T> class:

HashSet<MyEnum> = new HashSet<MyEnum>();
// add them here

This collection is very efficient in lookups and ensures that all items are unique. You can try to add an item which was already in the set, then Add returns false.

Since enum is a value type you can use it directly. If you want to use a custom class you have to ensure that it overrides Equals+GetHashCode. Another option is to pass a custom IEqualityComparer<T> to this constructor.

Upvotes: 4

Maz H
Maz H

Reputation: 151

This program contains a source array that contains several duplicated strings. It eliminates duplicate strings in the array. The program calls the HashSet constructor to transform the array elements into a set data structure.

class Program
{
    static void Main()
    {
    // Input array that contains three duplicate strings.
    string[] array1 = { "cat", "dog", "cat", "leopard", "tiger", "cat" };

    // Display the array.
    Console.WriteLine(string.Join(",", array1));

     // Use HashSet constructor to ensure unique strings.
     var hash = new HashSet<string>(array1);

     // Convert to array of strings again.
     string[] array2 = hash.ToArray();

     // Display the resulting array.
     Console.WriteLine(string.Join(",", array2));
     }
}

Upvotes: 1

Joakim Skoog
Joakim Skoog

Reputation: 786

You can use something that is called a HashSet. Rembember that it's good practice to implement IEqualityComparer for the objects that you want to use in the HashSet.

Upvotes: 0

Related Questions