2012-03-23 32 views
1

我想用LINQ對值進行排序,但我無法確定ToDictionary()方法是如何工作的。在vb.net中用linq對字典進行排序

我能找到的所有例子都在c#中。

這裏是我的代碼

Dim f As Dictionary(Of String, String) = (From value In projectDescriptions.Values 
              Order By value Ascending 
              Select value).ToDictionary(???) 

UPDATE

最後,我才意識到這是愚蠢的。對不起

我做了一個列表(keyValuePair的(字符串,字符串))

而且排序我的名單,我做

mylist.OrderBy(Function(x) x.Value).ToList() 

希望這會幫助別人

回答

3

你說你沒有找到這個例子,但檢查MSDN here。像下面的東西應該在VB中工作。

'not sure what the key is, but use whichever property you'd like 
Dim f As Dictionary(Of String, String) = 
     (From value In projectDescriptions.Values 
     Order By value Ascending 
     Select value).ToDictionary(Function(p) p.Key) 

但是,如果你在字典中再存放排序的枚舉,它成爲無序,這是一般的字典或地圖的屬性,也正是字典是如此之快,廣受歡迎。如果你需要排序,也許你想用SortedDictionary來代替?

+0

你說得對,我剛剛意識到我的問題有多愚蠢。抱歉 – Marc 2012-03-23 18:04:17

3

可你剛使用SortedDictionary


此外,在C#中要實現將類似於以下內容:

// enumerate dic itself, not just dic.Values 
(from p in dic 
orderby p.Value ascending 
select new KeyValuePair<string, string>(p.Key, p.Value) 
// or new { Key = p.Key, Value = p.Value }) 
    .ToDictionary(p => p.Key, p => p.Value); 

什麼不一樣的,以

dic.OrderBy(p => p.Value).ToDictionary(p => p.Key, p => p.Value); 
        // or .ToDictionary(p => p.Key); 
+0

是不是按鍵排序? – Marc 2012-03-23 15:23:18

+0

好吧,我要試試這個 – Marc 2012-03-23 15:28:45

1

字典不會使有關訂單的任何擔保的條目。我建議你選擇條目並將其轉換爲那些KeyValuePairs的列表:

Dim f = projectDescriptions.OrderBy(Function(p) p.Value).ToList() 

更新:如果你看一下the documentation at MSDN,你會發現,它明確指出,「爲了在返回的項目未定義「。真的。做不是期望一個字典被定購。

+1

你會得到'List >'not'Dictionary ' – abatishchev 2012-03-23 15:35:55

+0

這個答案爲什麼downvoted? Botz是正確的,不能保證字典的順序,所以按價值排序字典是沒有意義的。 – 2012-03-23 15:36:12

+2

@abatishchev是不是他建議的?看Botz的文字。 – Abel 2012-03-23 15:37:36

相關問題