我在c#中有两个字典。C#:使用LINQ关于值合并两个字典
两个字典及其calues是
Dictionary<int,List<string>> D1 = new Dictionary<int,List<string>>();
Dictionary<int,List<string>> D2= new Dictionary<int,List<string>>();
Dictionary<int,List<string>> D3 new Dictionary<int,List<string>>();
D1[1] = new List<string>{"a","b"};
D1[2] = new List<string>{"c","d"};
D1[3] = new List<string>{"e","f"};
D1[4] = new List<string>{"h"};
凡1,2,3和4是词典D1的密钥
D2[1] = new List<string>{"a","b"};
D2[2] = new List<string>{"c","d"};
D2[3] = new List<string>{"e","f"};
D2[4] = new List<string>{"g"};
D2[5] = new List<string>{"b","h"};
D2[6] = new List<string>{"f","l"};
D2[7] = new List<string>{"z"};
凡1,2,3,4,5,6和图7是解释D2的密钥
然后输出字典包含此值,
D3[1] = {"a","b","h"}
D3[2] = {"c","d"}
D3[3] = {"e","f","l"}
注: 请把输入字典比1.Thats值大于为什么我消除了D1 [4],D2 [4]和D2 [7]
这里是我的代码:
List<int> l_lstTempNets = new List<int>(D1.Keys);
int l_nCount = 0;
for (int l_nData = 0; l_nData < l_lstTempNets.Count; l_nData++)
{
D3.Add(l_nCount, D1[l_lstTempNets[l_nData]]);
l_nCount++;
}
l_lstTempNets = new List<int>(D2.Keys);
for (int l_nData = 0; l_nData < l_lstTempNets.Count; l_nData++)
{
D3.Add(l_nCount, D2[l_lstTempNets[l_nData]]);
l_nCount++;
}
List<int> l_lstOuter = new List<int>(D3.Keys);
List<int> l_lstInner = new List<int>(D3.Keys);
for (int l_nOuter = 0; l_nOuter < l_lstOuter.Count; l_nOuter++)
{
if (D3.ContainsKey(l_lstOuter[l_nOuter]) == false)
continue;
List<string> l_lstOuterValue = D3[l_lstOuter[l_nOuter]];
l_lstOuterValue.Sort();
if (l_lstOuterValue.Count == 0 || l_lstOuterValue.Count == 1)
{
D3.Remove(l_lstOuter[l_nOuter]);
continue;
}
for (int l_nInner = 0; l_nInner < l_lstInner.Count; l_nInner++)
{
if (l_lstOuter[l_nOuter] != l_lstInner[l_nInner])
{
if (D3.ContainsKey(l_lstInner[l_nInner]) == false)
continue;
List<string> l_lstInnerValue = new List<string>(D3[l_lstInner[l_nInner]]);
l_lstInnerValue.Sort();
for (int l_nOuterData = 0; l_nOuterData < l_lstOuterValue.Count; l_nOuterData++)
{
if (l_lstInnerValue.Contains(l_lstOuterValue[l_nOuterData]))
{
for (int l_nInnerData = 0; l_nInnerData < l_lstInnerValue.Count; l_nInnerData++)
{
if (l_lstOuterValue.Contains(l_lstInnerValue[l_nInnerData]) == false)
{
l_lstOuterValue.Add(l_lstInnerValue[l_nInnerData]);
}
}
IsExists = true;
break;
}
else
{
IsExists = false;
}
}
}
else
IsExists = false;
if (IsExists)
{
if (D3.ContainsKey(l_lstInner[l_nInner]))
D3.Remove(l_lstInner[l_nInner]);
}
}
}
是否有可能使用LINQ 如果您有任何疑问,PLZ让我知道
我不明白合并规则 – Andrey 2010-06-28 11:59:30
我看不出为什么在这里使用字典 – 2010-06-28 12:16:15
这真的不是很清楚你在这里做什么 - 起初我以为你想要一个合并字典,其中每个价值是源值的联合,但现在我认为你代表了一个链表?或者其他的东西? – AakashM 2010-06-29 07:02:27