如何在c# .Net 3.5中对HashSet<string>
进行排序?
你不能。按照定义,HashSet
不是有序的。
如果你需要一个有序的哈希集合,那么你应该使用SortedSet
。它提供的方法本质上是 HashSet
方法的超集,包括对其内容进行排序的能力。
HashSet
也没有不同的值。所以我真的不知道你评论的重点是什么。 - Cody GrayHashSet<string> 按设计不是排序的。如果您想要对这些项目进行排序一次(不会经常发生),那么您可以使用 OrderBy LINQ 方法(因为 HashSet<string> 实现了 IEnumerable<string>): hs.OrderBy(s => s);
如果您需要排序的哈希集,那么您可以使用 SortedDictionary 类-只需将某个虚拟类型 (例如bool) 用作TValue泛型参数。
SortedSet类在.NET 3.5中不可用。
OrderBy
方法,可以使用 IComparer(例如: http://msdn.microsoft.com/en-us/library/bb549422.aspx) 或者将你的比较器与一些 lambda 表达式一起内联使用 (我通常使用谓词进行比较,如下所示)。 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
*/
HashSet
不是有序的。你想创建一个有序的副本作为数组吗? - svick