比较两个 List> 的正确方法在 C# 2.0 中
这是 C# 2.0 中比较的正确方法吗(无 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样做会更简单、更快:
It would be simpler and faster to:
马塞洛是对的,KeyValuePairs 列表总是更好地表示为字典,除非您由于某种原因希望能够拥有重复的键。
尝试这样的事情:
Marcelo is right, a list of KeyValuePairs is always better represented as a dictionary UNLESS you want to be able to have duplicate keys for some reason.
Try something like this: