两个数组中的LINQ得到不同的,共同的项目 [英] Get different and common items in two arrays with LINQ

查看:114
本文介绍了两个数组中的LINQ得到不同的,共同的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个数组:

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

我试图做的是 -

What I'm trying to do is -


  1. list1的获取常见的物品和列表2 (例如:{2,3,4 })

  2. 获取不同的项目 list1的列表2 (例如:{1,5,6 })

  1. Get common items from list1 and list2 (eg. {"2", "3", "4"})
  2. Get different items list1 and list2 (eg. {"1", "5", "6"})

于是我试着LINQ和 -

So I've tried with LINQ and -

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"};

任何想法?

推荐答案

不知怎的,你必须得从别的地方这一结果。 (也许你正在写了 listDIff 的内容,第一,并认为它是从 listCommon )的相交方法的确实的给你存在于两个列表中的项目:

Somehow you have got that result from somewhere else. (Perhaps you are writing out the contents of listDIff first, and thought that it was from listCommon.) The Intersect method does give you the items that exists in both lists:

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

这篇关于两个数组中的LINQ得到不同的,共同的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆