Set the capacity of a HashSet to the actual number of elements it contains in CSharp

Description

The following code shows how to set the capacity of a HashSet to the actual number of elements it contains.

Example


/* ww w .j a v  a 2s . co m*/
using System;
using System.Collections.Generic;
public class MainClass
{
    public static void Main(String[] argv)
    {

        HashSet<int> Numbers = new HashSet<int>();

        for (int i = 0; i < 10; i++)
        {
            Numbers.Add(i);
        }

        Console.WriteLine(Numbers.Count);

        Numbers.Clear();
        Console.WriteLine(Numbers.Count);
        Numbers.TrimExcess();
        Console.WriteLine(Numbers.Count);
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary