C# 对 Hashset .Net 3.5 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10495770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:03:34  来源:igfitidea点击:

Sort a Hashset .Net 3.5

c#.net-3.5

提问by ViV

How can one sort a HashSet<string>in c# .Net 3.5 ?

如何HashSet<string>在 c# .Net 3.5 中对 a进行排序?

采纳答案by Cody Gray

You don't. By definition, a HashSetis not sorted.

你没有。根据定义, aHashSet未排序。

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.

如果你想要一个排序的哈希集,那么你应该使用SortedSet. 它公开的方法本质上是 提供的方法的超集HashSet,包括对其内容进行排序的能力。

回答by ericosg

You can use the OrderBymethod, 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).

您可以使用该OrderBy方法,即 IComparer(即http://msdn.microsoft.com/en-us/library/bb549422.aspx)或将您的比较器与一些 lambdas 内联使用(我通常使用谓词进行比较,如下所示)。

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

阅读更多:http: //msdn.microsoft.com/en-us/library/bb534966.aspx

回答by Augi

HashSet<string> is not sorted by design. If you want to sort the items once(~not often) then you can use OrderByLINQ method (because HashSet<string> implements IEnumerable<string>): hs.OrderBy(s => s);

HashSet<string> 不是按设计排序的。如果您想对项目进行一次排序(~不经常),那么您可以使用OrderByLINQ 方法(因为 HashSet<string> 实现了 IEnumerable<string>):hs.OrderBy(s => s);

If you need sorted hashsetthen you can use SortedDictionaryclass - just use some dummy type (i.e. bool) for TValuegeneric parameter.

如果您需要排序的哈希集,那么您可以使用SortedDictionary类 - 只需为TValue通用参数使用一些虚拟类型(即bool)。

The SortedSetclass is not available in .NET 3.5.

SortedSet的类不可用在.net 3.5。