2013-06-11 45 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();