Прочетете на английски Редактиране

Споделяне чрез


HashSet<T>.TrimExcess Method

Definition

Overloads

TrimExcess()

Sets the capacity of a HashSet<T> object to the actual number of elements it contains, rounded up to a nearby, implementation-specific value.

TrimExcess(Int32)

Sets the capacity of a HashSet<T> object to the specified number of entries, rounded up to a nearby, implementation-specific value.

TrimExcess()

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

Sets the capacity of a HashSet<T> object to the actual number of elements it contains, rounded up to a nearby, implementation-specific value.

C#
public void TrimExcess();

Examples

The following example creates and populates a HashSet<T> collection, and then clears the collection and releases the memory referenced by it.

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

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

Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);

Numbers.Clear();
Numbers.TrimExcess();

Console.Write("Numbers contains {0} elements: ", Numbers.Count);
DisplaySet(Numbers);

void DisplaySet(HashSet<int> set)
{
    Console.Write("{");
    foreach (int i in set)
    {
        Console.Write(" {0}", i);
    }
    Console.WriteLine(" }");
}

/* This example produces output similar to the following:
* Numbers contains 10 elements: { 0 1 2 3 4 5 6 7 8 9 }
* Numbers contains 0 elements: { }
*/

Remarks

You can use the TrimExcess method to minimize a HashSet<T> object's memory overhead once it is known that no new elements will be added. To completely clear a HashSet<T> object and release all memory referenced by it, call this method after calling the Clear method.

This method is an O(n) operation, where n is Count.

Applies to

.NET 10 и други версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

TrimExcess(Int32)

Source:
HashSet.cs

Sets the capacity of a HashSet<T> object to the specified number of entries, rounded up to a nearby, implementation-specific value.

C#
public void TrimExcess(int capacity);

Parameters

capacity
Int32

The new capacity.

Exceptions

The specified capacity is lower than the count of entries.

Applies to

.NET 10 и .NET 9
Продукт Версии
.NET 9, 10