2013-03-27 89 views
3

排序我有一個字典在字典C#

Dictionary<string, string> rList = new Dictionary<string, string>(); 
rList .Add("https://stackoverflow.com/a/b/c", "35"); 
rList .Add("https://stackoverflow.com/a/c/f/v", "25"); 
rList .Add("https://stackoverflow.com/a/r/d/c/r/v", "29"); 
rList .Add("/a", "21"); 
rList .Add("https://stackoverflow.com/a/f, "84"); 

我只想排序依據的「/」出現在密鑰號的數量本字典。我的預計了看跌期權,

("https://stackoverflow.com/a/r/d/c/r/v", "29") 
("https://stackoverflow.com/a/c/f/v", "25") 
("https://stackoverflow.com/a/b/c", "35") 
("https://stackoverflow.com/a/f, "84") 
("/a", "21") 
+0

這篇文章解釋了回答你的問題 HTTP:/ /stackoverflow.com/questions/15667684/sorting-in-dictionary-c-sharp – rajkumarts 2013-03-27 19:28:20

+1

@rajkumarts:你只是與這個問題有關。 – 2013-03-27 19:44:48

回答

12

Dictionary<TKey, TValue>類型是在.net中的無序集合。如果您想要訂購,則需要使用SortedDictionary<TKey, TValue>,並提供一個自定義IComparer<string>,它可以計算字符串中的/值。

sealed class SlashComparer : IComparer<string> { 
    static int CountSlashes(string str) { 
    if (String.IsNullOrEmpty(str)) { 
     return 0; 
    } 

    int count = 0; 
    for (int i = 0; i < str.Length; i++) { 
     if (str[i] == '/') { 
     count++; 
     } 
    } 
    return count; 
    } 

    public int Compare(string left, string right) { 
    int leftCount = CountSlashes(left); 
    int rightCount = CountSlashes(right); 
    return rightCount - leftCount; 
    } 
} 

要與SortedDictionary您需要更改的唯一的事情用的是聲明

var comparer = new SlashComparer(); 
var rList = new SortedDictionary<string, string>(comparer); 

的代碼的其餘部分可以保持不變

+0

感謝JaredPar,你能否提供一個示例代碼來處理SortedDictionary。 – ocp 2013-03-27 19:39:23

+0

@ocp添加了一些示例代碼。 – JaredPar 2013-03-27 19:42:23

+0

非常感謝...它的作品完美:) – ocp 2013-03-27 19:50:45

3

由於JaredPar回答已經Dictionary<TKey, TValue>內容沒有指定的順序。但是,你可以得到List<KeyValuePair<TKey, TValue>>與所需的順序:

List<KeyValuePair<string, string>> results = rList.OrderByDescending(x => x.Key.Count(c => c == '/')).ToList(); 
1

試試這個:

var result = rList.OrderBy(input => input.Key.Select(c => c == '/').Count()).Reverse().ToList(); 
+2

這不會工作。這裏的最終產品是一個總是無序的'Dictionary '。 OP想要訂購的價值 – JaredPar 2013-03-27 19:34:16

+0

現在它是正確的。首先它是以相反的順序。 – 2013-03-27 19:39:11

+0

只要以「ToDictionary」調用結束,它就會出錯。一個'Dictionary'總是** **無序的。無論您將值添加到字典中的順序如何,都無關緊要。他們被允許在枚舉期間返回一個不同的頁面 – JaredPar 2013-03-27 19:43:15

0

從linqpad:

void Main() 
{ 
    Dictionary<string, string> rList = new Dictionary<string, string>(); 
    rList .Add("https://stackoverflow.com/a/b/c", "35"); 
    rList .Add("https://stackoverflow.com/a/c/f/v", "25"); 
    rList .Add("https://stackoverflow.com/a/r/d/c/r/v", "29"); 
    rList .Add("/a", "21"); 
    rList .Add("https://stackoverflow.com/a/f", "84"); 

    var x = from a in rList 
     let i = a.Key.ToCharArray().Count (k => k.Equals('/')) 
     orderby i descending 
     select a; 

    x.Dump(); 
}