这是在C#2.0中进行比较的正确方法(NO LINQ)。
下面的代码工作正常,但我认为这不是比较好的方法。
List<KeyValuePair<string, foo>> list1 = new List<KeyValuePair<string, foo>>();
List<KeyValuePair<string, foo>> list2 = new List<KeyValuePair<string, foo>>();
List<foo> diffList = new List<foo>();
list1.Add(new KeyValuePair<string, foo>("1", new foo("1", new Cost(1.0)));
list1.Add(new KeyValuePair<string, foo>("2", new foo("2", new Cost(2.0)));
list1.Add(new KeyValuePair<string, foo>("3", new foo("3", new Cost(3.0)));
list1.Add(new KeyValuePair<string, foo>("5", new foo("5", new Cost(5.0)));
list2.Add(new KeyValuePair<string, foo>("1", new foo("1", new Cost(1.0));
list2.Add(new KeyValuePair<string, foo>("2", new foo("2", new Cost(2.1)));
list2.Add(new KeyValuePair<string, foo>("4", new foo("4", new Cost(4.0));
list2.Add(new KeyValuePair<string, foo>("6", new foo("6", new Cost(6.0)));
list2.Add(new KeyValuePair<string, foo>("7", new foo("7", new Cost(7.0)));
foreach (KeyValuePair<string, foo> pair1 in list1)
{
bool b = true;
foreach (KeyValuePair<string, foo> pair2 in list2)
{
if (pair2.Key == pair1.Key)
{
if (pair2.Value.Equals(pair1.Value))
{
list2.Remove(pair2);
break;
}
else
{
diffList.Add(pair2.Value);
diffList.Add(pair1.Value);
list2.Remove(pair2);
b = false;
break;
}
}
else
{
diffList.Add(pair2.Value);
diffList.Add(pair1.Value);
list2.Remove(pair2);
b = false;
break;
}
}
if (list2.Count == 0 && b)
{
diffList.Add(pair1.Value);
}
}
foreach (KeyValuePair<string, foo> pair2 in list2)
{
diffList.Add(pair2.Value);
}
答案 0 :(得分:2)
它会更简单,更快捷:
答案 1 :(得分:2)
Marcelo是对的,KeyValuePairs列表总是更好地表示为字典,除非您希望能够出于某种原因重复键。
尝试这样的事情:
var a = list1.ToDictionary(i => i.Key, i => i.Value);
var b = list2.ToDictionary(i => i.Key, i => i.Value);
var result = new List<foo>();
foreach (var entry in a)
{
if (b.ContainsKey(entry.Key)
&& entry.Value != b[entry.Key])
{
result.Add(entry.Value);
result.Add(b[entry.Key]);
}
}
foreach (var entry in b)
{
if (a.ContainsKey(entry.Key)
&& entry.Value != a[entry.Key]
&& !result.Contains(entry.Value))
{
result.Add(entry.Value);
result.Add(a[entry.Key]);
}
}