2013-10-25 56 views
0

创建两个列表一样,比较C#列表

  var list = new List<KeyValuePair<string, string>>(); 
      list.Add(new KeyValuePair<string, string>("1", "abc")); 
      list.Add(new KeyValuePair<string, string>("2", "def")); 
      list.Add(new KeyValuePair<string, string>("3", "ghi")); 


      var list2 = new List<KeyValuePair<string, string>>(); 
      list.Add(new KeyValuePair<string, string>("1", "abc")); 
      list.Add(new KeyValuePair<string, string>("2", "def")); 
      list.Add(new KeyValuePair<string, string>("3", "ghi")); 
      list.Add(new KeyValuePair<string, string>("4", "jkl")); 

      var unmatchedlist= new List<KeyValuePair<string, string>>(); 

如何比较这两个lists.now我需要list.Add(新KeyValuePair( “4”, “JKL”));(因为它不在第一个列表中,但它在第二个列表中)在不匹配的列表中?

+0

如果你解释你为什么要这么做,这可能会有所帮助。就目前而言,'list = list2;'是一个解决方案(但我认为这不是你想要的)。另外,在你的比较中,如果两个列表具有相同的元素,但是按不同的顺序,你认为两个列表是否相等? –

回答

0

这将让你列表2和表之间的差异:

var unmatched = list2.Except(list); 

然后,只需添加出现在无与伦比的项目到列表中。

+0

好主意,但它应该是其他方式,我认为:) – BartoszKP

+0

它看起来像是在声明list2后更多的项目被添加到前面的列表变量。不知道这是否正确。但是由此OP可以在需要的地方切换。 – Ric

+0

它看起来并不重要 - OP显然想要做'list.Add',所以'list'中缺少的东西是有趣的:) – BartoszKP

0

检查这样

//This will be empty 
var difference1 = list1.Except(list2); 

或者其他方式以防万一

//This will contain item 4 
var difference2 = list2.Except(list1); 
2

一个办法做到这一点:

list1 = list1.Union(list2); 

OR:

list1.AddRange(list1.Except(list2));