有一些類似的問題,但不幸的是,我發現沒有一個問題能提供我需要的答案。幫助表示贊賞。
第一個問題
我有一本字典,可以說如下(例如簡化):
IDictionary<string, string> Beatles = new Dictionary<string, string>();
Beatles.Add("Singer", "John");
Beatles.Add("Drummer", "Ringo");
Beatles.Add("Guitar", "Paul");
Beatles.Add("Bass", "George");
是否可以根據下面的字串陣列或串列重新排序字典(編輯 - 并輸出一個僅包含重新排序值的串列,因為有人澄清字典沒有順序):
string[] reorderList = {"Guitar","Bass","Singer","Drummer"};
編輯 - 我希望輸出是一個包含以下順序的串列:“Paul”、“George”、“John”、“Ringo”
次要問題
假設我的排序字串中沒有包含任何 Dictionary 專案,如下所示:
string[] locations = {"Guitar","Singer","Drummer"};
我希望將所有丟失的專案(在這種情況下只是“鼓”)自動添加到末尾。那可能嗎?
uj5u.com熱心網友回復:
這是一個快速擴展,它將回傳您所要求的內容:
public static class DictionaryExtension
{
public static List<T> CustomSort<TK, T>(this IDictionary<TK, T> src, TK[] sortList)
{
// items in the sortList
var output = (from key in sortList where src.ContainsKey(key) select src[key]).ToList();
// remaining "other" items
output.AddRange((from item in src where !sortList.Contains(item.Key) select item.Value).OrderBy(o => o));
return output;
}
}
注意:它不檢查 IComparable 所以 YMMV。如果您在 reorderList 中有重復的鍵,您將在結果中得到重復的值。
uj5u.com熱心網友回復:
這是一個非常有趣的問題。首先,正如大家所建議的那樣,您不能重新排序 Dictionary。但是,您可以通過運行以下代碼來實作所需的輸出
var pass1 = reorderList.Select(x => Beatles.ContainsKey(x) ? Beatles[x] : null).Where(x => x != null); //Adds desired ordered list of Dictionary values to the list
var result = pass1.Union(Beatles.Values.Except(pass1)).ToList(); //Appends remaining values, if any, to list
變數result將具有您想要的輸出。
更新
更新了上面的代碼以處理無效值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449213.html
