21

例如,我有两个数组:

var list1 = string[] {"1", "2", "3", "4", "5", "6"};
var list2 = string[] {"2", "3", "4"};

我想做的是——

  1. list1从and获取常用项目list2(例如 {"2", "3", "4"})
  2. 获取不同的项目list1list2(例如。{“1”,“5”,“6”})

所以我尝试过使用 LINQ 并且 -

var listDiff = list1.Except(list2); //This gets the desire result for different items

但,

var listCommon = list1.Intersect(list2); //This doesn't give me desire result. Comes out as {"1", "5", "6", "2", "3", "4"};

有任何想法吗?

4

1 回答 1

29

不知何故,你从其他地方得到了这个结果。(也许您正在写出listDIfffirst 的内容,并认为它来自listCommon。)该Intersect方法确实为您提供了两个列表中存在的项目:

var list1 = new string[] {"1", "2", "3", "4", "5", "6"};
var list2 = new string[] {"2", "3", "4"};
var listCommon = list1.Intersect(list2);
foreach (string s in listCommon) Console.WriteLine(s);

输出:

2
3
4
于 2012-05-18T07:14:04.480 回答