How can one sort a HashSet<string>
in c# .Net 3.5 ?
问题:
回答1:
You don't. By definition, a HashSet
is not sorted.
If you want a sorted hash set, then you should use a SortedSet
. The methods it exposes are essentially a superset of those provided by HashSet
, including the ability to sort its contents.
回答2:
You can use the OrderBy
method, either an IComparer (i.e. http://msdn.microsoft.com/en-us/library/bb549422.aspx ) or using your comparer inline with some lambdas (i usually use predicates for my comparisons as per below).
See as per link:
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void OrderByEx1()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
}
/*
This code produces the following output:
Whiskers - 1
Boots - 4
Barley - 8
*/
Read more: http://msdn.microsoft.com/en-us/library/bb534966.aspx
回答3:
HashSet<string> is not sorted by design. If you want to sort the items once (~not often) then you can use OrderBy LINQ method (because HashSet<string> implements IEnumerable<string>): hs.OrderBy(s => s);
If you need sorted hashset then you can use SortedDictionary class - just use some dummy type (i.e. bool) for TValue generic parameter.
The SortedSet class is not available in .NET 3.5.