當(dāng)每個(gè)鍵共享一個(gè)值時(shí),我試圖生成一個(gè)字符串鍵組合列表,下面是我的代碼的摘錄var keyCombos = new List<List<string>>();var dict = new Dictionary<string, List<int>>();dict.Add("A", new List<int>() { 1, 2, 3 });dict.Add("B", new List<int>() { 1, 2, 3, 4 });dict.Add("C", new List<int>() { 1, 4, 5 });上面是一個(gè)字典,其中包含一個(gè)字符串 Key 和一個(gè)整數(shù)列表作為其值,該keyCombos列表將保存共享整數(shù)列表值的所有鍵組合,我的預(yù)期輸出keyCombos如下["A","B","C"] //1 is common["A","B"] //1,2,3 are common["B","C"] //1,4 are common["C"] //5組合的順序并不重要,到目前為止,我的代碼使用各種foreach循環(huán),我只能組合 2 個(gè)鍵,而不是 1 或 3。foreach(var k1 in dict.Keys) { List<int> a1 = dict[k1]; foreach (var k2 in dict.Keys) { if (k1 != k2) { List<int> a2 = dict[k2]; if(a1.Intersect(a2).Count()>0) { var matches = false; foreach(var combo in keyCombos) { if ((combo.Contains(k1)) && (combo.Contains(k2))) { matches = true; } } if (!matches) { keyCombos.Add(new List<string>() { k1, k2 }); } } else { keyCombos.Add(new List<string>() { k1 }); } } } }
3 回答

呼如林
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
我相信最簡單的方法是首先從字典中獲取不同的整數(shù),然后遍歷它們并使用 linq 獲取該整數(shù)在列表中的鍵。喜歡:
var distinctKeyCombos = dict.SelectMany(x => x.Value).Distinct();
foreach(var i in distinctKeyCombos)
{
var keys = dict.Where(p => p.Value.Contains(i)).Select(p => p.Key);
}
- 3 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報(bào)
0/150
提交
取消