[英]LINQ - How to Group By with Dictionary <string, string[]>?
我有一本這樣的字典:
Dictionary<string, string[]> dic = new Dictionary<string,string[]>(){
{"A", new string [] {"1", "2", "$", "3", "4"}},
{"B", new string [] {"5", "6", "$", "7", "8"}},
{"C", new string [] {"9", "10", "@", "11", "12"}}
};
我想把它變成這樣的新詞典:
Dictionary<string, List<string[]>> res = new Dictionary<string,List<string[]>>{
{"$", new List<string[]> {
new string [] {"1", "2", "A", "3", "4"},
new string [] {"5", "6", "B", "7", "8"}
}
},
{"@", new List<string[]> {
new string [] {"9", "10", "C", "11", "12"}
}
}
};
因此新的Key成為舊字符串數組的第3個元素,並將舊的Key添加到新的字符串數組中。
注意-不需要將舊的Key放置為新數組的第3個元素,但是對於每個新數組,它確實必須位於相同的索引中。
我開始嘗試為此使用一些LINQ,但是無法將我的頭包裹在整個事情上-這是:
Dictionary<string, string[]> test = dic.GroupBy(x => x.Value[2])
.ToDictionary(s => s.Key, s => s.Select(x => x.Key).ToArray());
僅可用於創建另一個字符串鍵控數組值字典,其中該鍵正確地變成了第三個元素,但值只是舊鍵。
一種可能的解決方案:
Dictionary<string, string[]> dic = new Dictionary<string,string[]>(){
{"A", new string [] {"1", "2", "$", "3", "4"}},
{"B", new string [] {"5", "6", "$", "7", "8"}},
{"C", new string [] {"9", "10", "@", "11", "12"}}
};
var res = dic.Select(p => new KeyValuePair<string, string[]>(
p.Value[2],
p.Value.Select((v,i) => i == 2 ? p.Key : v).ToArray()))
.GroupBy(p => p.Key)
.ToDictionary(g => g.Key, g => g.Select(p => p.Value).ToList());
var replacedIndex = 2;
var newDictionary =
oldDictionary.GroupBy(x => x.Value.ElementAt(replacedIndex))
.ToDictionary(group => group.Key, group => group.Select(x =>
{
var collection = x.Value;
collection[replacedIndex] = x.Key;
return collection;
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.