2013-06-11 42 views
3

我想获得一个独特的,按字母顺序排列的行业名称(字符串)列表。这里是我的代码:列表排序编译错误

HashSet<string> industryHash = new HashSet<string>(); 
List<string> industryList = new List<string>(); 
List<string> orderedIndustries = new List<string>(); 

// add a few items to industryHash 

industryList = industryHash.ToList<string>(); 
orderedIndustries = industryList.Sort(); //throws compilation error 

最后一行抛出一个编译错误: “无法隐式转换类型‘无效’到“System.Collections.Generic.List”

我在做什么错?

+1

当你在这,你可能也使用OrderedSet BTW。 http://msdn.microsoft.com/en-us/library/dd412070.aspx – C4stor

回答

3

List.Sort排序原始列表,不返回一个新的。因此,无论使用此方法或Enumerable.OrderBy + ToList

高效:

industryList.Sort(); 

效率较低:

industryList = industryList.OrderBy(s => s).ToList(); 
1

它就地对列表进行排序。如果您想要副本,请使用OrderBy

2

Sort是一个无效方法,您无法从此方法检索值。你可以看一下this article

您可以使用OrderBy()订购列表

+0

您引用的文章是法文版。 – dmr

+0

Ooops。修正! :) –

1

这样做:

HashSet<string> industryHash = new HashSet<string>(); 
List<string> industryList = new List<string>(); 

// add a few items to industryHash 

industryList = industryHash.ToList<string>(); 
List<string> orderedIndustries = new List<string>(industryList.Sort()); 

注意:不要让未排序清单,所以没有真正的重点只做industryList.Sort()

+0

不,我不知道。我只是没有意识到,我可以在没有复制的情况下对列表进行排序。 – dmr

+0

好吧,你们都设置然后^^ – C4stor

0

一种选择是使用LINQ和删除industryList

HashSet<string> industryHash = new HashSet<string>(); 
//List<string> industryList = new List<string>(); 
List<string> orderedIndustries = new List<string>(); 

orderedIndustries = (from s in industryHash 
        orderby s 
        select s).ToList();