[英]Sorting in Dictionary C#
我有一本字典
Dictionary<string, string> rList = new Dictionary<string, string>();
rList .Add("/a/b/c", "35");
rList .Add("/a/c/f/v", "25");
rList .Add("/a/r/d/c/r/v", "29");
rList .Add("/a", "21");
rList .Add("/a/f, "84");
我只想根據密鑰中存在的“/”數來對此字典進行排序。 我的預期出局是,
("/a/r/d/c/r/v", "29")
("/a/c/f/v", "25")
("/a/b/c", "35")
("/a/f, "84")
("/a", "21")
Dictionary<TKey, TValue>
類型是.Net中的無序集合。 如果您想要訂購,那么您需要使用SortedDictionary<TKey, TValue>
並提供自定義IComparer<string>
,它計算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);
其余代碼可以保持不變
由於JaredPar已經回答了Dictionary<TKey, TValue>
內容沒有指定順序。 但是,您可以按所需順序獲取List<KeyValuePair<TKey, TValue>>
:
List<KeyValuePair<string, string>> results = rList.OrderByDescending(x => x.Key.Count(c => c == '/')).ToList();
嘗試這個:
var result = rList.OrderBy(input => input.Key.Select(c => c == '/').Count()).Reverse().ToList();
來自linqpad:
void Main()
{
Dictionary<string, string> rList = new Dictionary<string, string>();
rList .Add("/a/b/c", "35");
rList .Add("/a/c/f/v", "25");
rList .Add("/a/r/d/c/r/v", "29");
rList .Add("/a", "21");
rList .Add("/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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.