对两个字典(键相同就认为相同)求交集、并集和差集(List和数组同理)
Dictionary<string, string> dic1 = new Dictionary<string, string>();
Dictionary<string, string> dic2 = new Dictionary<string, string>();
for (int i=0 ;i < 20; i += 2)
{
dic1.Add("Key"+i,"Value"+i);
}
for (int i=0;i<20; i += 4)
{
dic2.Add("Key" + i, "Value" + i);
}
//求交集
var inter = dic1.Keys.Intersect(dic2.Keys);
string temp = "";
foreach (var key in inter)
{
temp += key + " : " + dic1[key] + "\n";
}
Console.WriteLine("交集:\n" + temp);
//求差集
var exc = dic1.Keys.Except(dic2.Keys);
string temp2 = "";
foreach (var e in exc)
{
temp2 += e + " : " + dic1[e] + "\n";
}
Console.WriteLine("差集:\n" + temp2);
//求并集,
var union = dic1.Keys.Union(dic2.Keys);
string temp3 = "";
foreach (var u in union)
{
if (dic1.ContainsKey(u))
{
temp3 += u + ":" + dic1[u] + "\n";
}else
{
temp3 += u + ":" + dic2[u] + "\n";
}
}
Console.WriteLine("并集:\n" + temp3);
Console.ReadLine();