新彩天欢迎您!
幻海优品

.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<int> listInt = new List<int>();            listInt.Add(1);            listInt.Add(2);            listInt.Add(3);            List<int> listInt1 = new List<int>();            listInt1.Add(2);            listInt1.Add(3);            listInt1.Add(4);            IEnumerable<int> 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<int> listInt = new List<int>();            listInt.Add(1);            listInt.Add(2);            listInt.Add(3);            List<int> listInt1 = new List<int>();            listInt1.Add(2);            listInt1.Add(3);            listInt1.Add(4);            IEnumerable<int> IEInt = listInt.Except(listInt1);            foreach (var i in IEInt)            {                Console.WriteLine(i);               }            Console.ReadKey();        }    }}

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除