[英]Check if multiple dictionaries with the same keys have the same values
假設我有一系列字典。 所有的字典都有完全相同的鍵。 對於每個鍵,如果該鍵的值與至少 1 個其他字典的值相同,我想返回數組中字典的索引。
例如,如果有一個鍵 "a" 和ArrayOfDictionaries[0]["a"]
和ArrayOfDictionaries[2]["a"]
都計算為 7,我想添加到一個空dictionary<string, int[]>
對 ("a", [0, 2])。
我對如何實現這一目標的邏輯感到非常困惑。
如果我理解正確,您的邏輯可能看起來像這樣。 FilteredDictionary 將得到最終結果。
var resultDictionary = new Dictionary<string, List<int>>();
var filteredDictonary = new Dictionary<string, int[]>();
var arrayOfDictionaries = new Dictionary<string, int>[]
{
new Dictionary<string, int> { { "a", 7 },{ "b",5},{ "c", 10 } },
new Dictionary<string, int> { { "a", 8 },{ "b",6},{ "c", 10 } },
new Dictionary<string, int> { { "a", 7 },{ "b",7},{ "c", 10 } },
};
for (var j = 0; j < arrayOfDictionaries.Length; j++)
{
foreach (var i in arrayOfDictionaries[j])
{
var uniqueKey = i.Key + i.Value.ToString();
if (resultDictionary.ContainsKey(uniqueKey))
{
resultDictionary[uniqueKey].Add(j);
}
else
{
resultDictionary.Add(uniqueKey, new List<int> { j });
}
}
}
filteredDictonary = resultDictionary.Where(a => a.Value.Count() > 1).Select(a => a).ToDictionary(kv => kv.Key.Substring(0,1), kv => kv.Value.ToArray());
如果您的字典數組被命名為src
,那么對於每個鍵,您可以將所有具有匹配值的字典分組,然后轉換為位置列表。 將結果轉換為Dictionary
取決於您希望如何處理產生的重復鍵。
var ans2 = src[0].Keys.SelectMany(k => src.Select((d, i) => new { Key = k, Value = d[k], pos = i })
.GroupBy(kvp => kvp.Value)
.Select(kvpg => new { Key = kvpg.First().Key, Matches = kvpg.Select(kvp => kvp.pos).ToList() })
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.