开发手册 欢迎您!
软件开发者资料库

.NET(C#) Linq Intersect和Except的使用

Linq是Language Integrated Query的简称,它是微软在.NET Framework 3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#) 中Linq的Intersect和Except操作符。

1、Intersect操作符

Intersect操作符会将两个输入序列中的重复元素,即同时存在于两个序列中的元素挑选出来,生成一个新的集合,也就是求交集。

例如,

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication{    class Program    {        static void Main(string[] args)        {             List listInt = new List();            listInt.Add(1);            listInt.Add(2);            listInt.Add(3);            List listInt1 = new List();            listInt1.Add(2);            listInt1.Add(3);            listInt1.Add(4);            IEnumerable IEInt = listInt.Intersect(listInt1);            foreach (var i in IEInt)            {                Console.WriteLine(i);               }            Console.ReadKey();        }    }}

2、Except操作符

Except操作符可以实现一种集合之间的减法运算,它返回两个序列中存在于第一个序列但不存在于第二个序列的元素所组成的新序列。

例如,

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication{    class Program    {        static void Main(string[] args)        {            List listInt = new List();            listInt.Add(1);            listInt.Add(2);            listInt.Add(3);            List listInt1 = new List();            listInt1.Add(2);            listInt1.Add(3);            listInt1.Add(4);            IEnumerable IEInt = listInt.Except(listInt1);            foreach (var i in IEInt)            {                Console.WriteLine(i);               }            Console.ReadKey();        }    }}