假设我有一个这样的字典
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 :(得分:4)
你不能指望字典被排序。相反,您可以使用SortedDictionary<string, string>
并将其构造函数传递给自定义IComparer<T>
。
答案 1 :(得分:2)
如果您可以使用IOrderedEnumerable KeyValuePairs,这将有效:
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
答案 2 :(得分: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()) {}
}
}