2014-09-03 69 views
0

我想有這樣根據在C#中的字符串值的長度排序字典

dict1 = {{[4,bcefgh]},{[5,abcefgh]},{[6,efgh]},{[7,bcefgh]},{[10,cefghi]}} 

我想根據字符串值的長度,在這本詞典對排序,而無需使用額外的環路一本字典,那就是結果應該是:

dict1 = {{[6,efgh]},{[4,bcefgh]},{[7,bcefgh]},{[10,cefghi]},{[5,abcefgh]}} 

我最初的答案是創建一個單獨的字典,有同樣的密鑰和相應的每個串的長度和遍歷對三分之一字典如下:

foreach (KeyValuePair<int,string> pair in dict1) 
{ 
    temp_dict.Add(pair.Key, pair.Value.Count()); 
} 

var items = from pair in temp_dict 
     orderby pair.Value ascending 
      select pair; 

foreach (KeyValuePair<int, int> pair in items) 
{ 
    result_dict.Add(pair.Key, dict1[pair.Key]); 
} 

但是,這一結果是現在的大數據集實用。

非常感謝

+0

不光是不切實際的,這是不正確。 'Dictionary'不保留項 – 2014-09-03 22:12:59

回答

4

你不能指望正在排序的字典。相反,你可以使用SortedDictionary<string, string>,並通過它的構造定製IComparer<T>

+0

'的IComparer ''中的SortedDictionary順序中''需要TKey',不'TValue' http://stackoverflow.com/a/3417518/1283124 – 2014-09-03 22:10:44

1

如果你可以用KeyValuePairs的IOrderedEnumerable生活,這將工作:

var dict1 = new Dictionary<int, string> 
{ 
    {4, "bcefgh"}, 
    {5, "abcefgh"}, 
    {6, "efgh"}, 
    {7, "bcefgh"}, 
    {10, "cefghi"} 
}; 

IOrderedEnumerable<KeyValuePair<int, string>> sortedDict = 
    dict1.OrderBy(i => i.Value.Length).ThenBy(i => i.Key); 


foreach (var keyValuePair in sortedDict) 
{ 
    Console.WriteLine(keyValuePair.Key + ": " + keyValuePair.Value); 
} 

// Output: 
// 6: efgh 
// 4: bcefgh 
// 7: bcefgh 
// 10: cefghi 
// 5: abcefgh 
0

這裏是我使用。一組有序的鍵值對。按值長度排序。

public class ValueSortedKeyValuePairSet : SortedSet<KeyValuePair <int, string>> 
    { 

     private class StringLengthComparerDecending : IComparer<KeyValuePair <int, string>> 
     { 
      public int Compare(KeyValuePair <int, string> x, KeyValuePair <int, string> y) 
      { 
       var lengthComparison = x.Value.Length.CompareTo(y.Value.Length); 
       return lengthComparison == 0 ? string.Compare(x.Value, y.Value, StringComparison.Ordinal) : lengthComparison; 
      } 
     } 

     public ValueSortedKeyValuePairSet() : base(new StringLengthComparerDecending()) {} 

     public ValueSortedKeyValuePairSet(IEnumerable<KeyValuePair <int, string>> e) : base(e, new StringLengthComparerDecending()) {}  
    } 
} 

演示:https://dotnetfiddle.net/pklISX