C# 使用 LINQ 获取两个数组中不同且常见的项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10648141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:39:03  来源:igfitidea点击:

Get different and common items in two arrays with LINQ

c#linq

提问by Ye Myat Aung

For example, I have two arrays:

例如,我有两个数组:

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

What I'm trying to do is -

我想做的是——

  1. Get common items from list1and list2(eg. {"2", "3", "4"})
  2. Get different items list1and list2(eg. {"1", "5", "6"})
  1. list1和获取公共项目list2(例如{“2”,“3”,“4”})
  2. 获取不同的项目list1list2(例如{“1”、“5”、“6”})

So I've tried with LINQ and -

所以我尝试过 LINQ 并且 -

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

But,

但,

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

Any ideas?

有任何想法吗?

采纳答案by Guffa

Somehow you have got that result from somewhere else. (Perhaps you are writing out the contents of listDIfffirst, and thought that it was from listCommon.) The Intersectmethod doesgive you the items that exists in both lists:

不知何故,你从其他地方得到了这个结果。(也许您正在写出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);

Output:

输出:

2
3
4