C# Linq获取两个List或数组的差集交集

List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
list1.Add(3);
List<int> list2 = new List<int>();
list2.Add(3);
list2.Add(4);
list2.Add(5);
//得到的结果是4,5 即减去了相同的元素。
List<int> list3 = list2.Except(list1).ToList();
foreach (int i in list3)
{
    MessageBox.Show(i.ToString());
}

合并两个数组,并去掉重复元素,然后排序

List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 12, 10 };
List<int> numbers2 = new List<int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
var newQuerty = numbers1.Concat(
from n in numbers2
where !numbers1.Contains(n)
select n
).OrderBy(n=>n);

合并两个数组,并去除合并后的重复数据, 并排序

int[] A={1,2,2,3,4,5,6,6,6};
int[] B={2,2,2,3,7,8,9,5};
List<int> list = new List<int>(A);
list.AddRange(B);
list.Sort();
//去除重复项
foreach (int i in list.Distinct<int>())
{
    Console.WriteLine(i);
}

取两个数组的相同元素

string[] names = {"Adams","Arthur","Buchanan","Tsbuchis","ShCian","FuchsiaLinda","DecheChen","Lotheer","FindLanciCade","SorchLand","JiangZheng","MisiiLoda","Gtod","Dfac","Lama","BakCades","Losangle","ZheWQ","GehengDahaLothi","ToryLandey","DakaLothy","BthLanda","MenNorth","Fith","FoxMain","DontM","Saobba","Del","Sala","Ghero","BhthLaPhda"};
IEnumerable<string> skip = names.Skip(10);
IEnumerable<string> take = names.Take(11);
//取出两个序列中交集部分,按理论应该输出JiangZheng
IEnumerable<string> intersect = skip.Intersect(take);//取出交集
foreach(varsinintersect)
{
     Console.WriteLine(s);
}
///Take();
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            var first3Numbers = numbers.Take(3); //从第一个元素开始,获取三个 return的是前面的数
            Console.WriteLine("First 3 numbers:");
            foreach (var n in first3Numbers)
            {
                Console.WriteLine(n);//结果 5 4 1
            }
///TakeWhile()
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            //在这里需要注意.使用TakeWhile获取小于6的元素,是从第一个元素开始,
            //一直到不满足其小于6这个条件为止.也就是执行到和9这个元素比较后,就结束比较了
            //可以想象一下执行过程.
            //5<6=true;4<6=true;1<6=true;3<6=true
            //9<6=false; 这里就停止继续比较了
            var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
            Console.WriteLine("First numbers less than 6:");
            foreach (var n in firstNumbersLessThan6)
            {
                Console.WriteLine(n);//结果为 5 4 1 3
            }
 ///Skip()
            ///
            /// int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            var allButFirst4Numbers = numbers.Skip(4); //跳过前四个元素,获取后面所有的元素
            Console.WriteLine("All but first 4 numbers:");
            foreach (var n in allButFirst4Numbers)
            {
                Console.WriteLine(n);//结果9 8 6 7 2 0
            }
  //SkipWhile()
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            //跳过不能被3整除的所有元素
            //这里和TakeWhiel又有些不一样。
            //TakeWhile遇到条件不满足的时候,就会return,
            //但是SkipWhile如果执行到能被三整除的数,那么其后面的元素就不会继续比较了
            //同样,想象一下执行过程
            //5%3!=0==true; 4%3!=0==true; 1%3!=0==true;
            //3%3!=0==false; 运行到这里的时候,后面的就不再比较.
            //所以输出结果中会有8、7、2、0这几个不满足条件的元素
            var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);
            foreach (var n in allButFirst3Numbers)
            {
                Console.WriteLine(n);//结果3 9 8 6 7 2 0
            }
            Console.ReadKey();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data; 
 
 
namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            IList<Student> oneStudents = new List<Student>();
            oneStudents.Add(new Student(1,false,"小新1","徐汇"));
            oneStudents.Add(new Student(2,false,"小新2","闵行"));
            oneStudents.Add(new Student(3, false, "小新3", "嘉定"));
            oneStudents.Add(new Student(4, false, "小新4", "闸北"));
 
            IList<Student> twoStudents = new List<Student>();
            twoStudents.Add(new Student(5, false, "小新5", "贵州"));
            twoStudents.Add(new Student(6, false, "小新6", "湖北"));
            twoStudents.Add(new Student(7, false, "小新7", "山东"));
            twoStudents.Add(new Student(8, false, "小新8", "西藏"));
 
            IList<Student> threeStudents = new List<Student>();
            threeStudents.Add(new Student(1, false, "小新1", "徐汇"));
            threeStudents.Add(new Student(2, false, "小新2", "闵行"));
            var bingji = oneStudents.Union(twoStudents, new StudentListEquality()).ToList();//并(全)集 
              var jiaoji = oneStudents.Intersect(threeStudents, new StudentListEquality()).ToList();//交集 
              var chaji = oneStudents.Except(threeStudents, new StudentListEquality()).ToList();//差集
 
              Console.WriteLine();
            Console.WriteLine("以下是并集的结果");            
            bingji.ForEach(x =>
            {
                Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString()+" "+x.Address.ToString());
      
            });
            Console.WriteLine();
            Console.WriteLine("以下是交集的结果");           
            jiaoji.ForEach(x =>
            {
                Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());
 
            });
 
            Console.WriteLine();
            Console.WriteLine("以下是差集的结果");            
            chaji.ForEach(x =>
            {
                Console.WriteLine(x.StudentId.ToString() + "    " + x.Sex.ToString() + "   " + x.Name.ToString() + " " + x.Address.ToString());
 
            });
        }
 
    }
 
 
 
 
 
    public class Student
    {
        public Student(int studentId, bool sex, String name, String address)
        {
            this.StudentId = studentId;
            this.Sex = sex;
            this.Name = name;
            this.Address = address;
        }
        public int StudentId { get; set; }
        public bool Sex { get; set; }
        public String Name { get; set; }
        public String Address { get; set; }
        
    }
    public class StudentListEquality : IEqualityComparer<Student>
    {
        public bool Equals(Student x, Student y)
        {
            return x.StudentId == y.StudentId;
        }
 
        public int GetHashCode(Student obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return obj.ToString().GetHashCode();
            }
        }
    }
 
 
 
}
以上运行的结果是:
以上的结果是重载了含有参数的IEqualityComparer<TSource> 方法,实现IEqualityComparer接口  对数据进行了重复过滤,如果不实现这个方法结果是
var bingji = oneStudents.Union(twoStudents).ToList();//并(全)集 
var jiaoji = oneStudents.Intersect(threeStudents).ToList();//交集 
var chaji = oneStudents.Except(threeStudents).ToList();//差集
但是对于List<T>的T是简单类型,如int  string  long 。。。。。是怎么样的呢?代码如下所示
IList<int> firstNumbers = new List<int>()
             {
                 1,2,3,4,5,6,7
 
             };
 
            IList<int> secondNumbers = new List<int>()
             {
 
                 8,9,10
 
             };
 
            IList<int> thressNumbers = new List<int>()
             {
 
                 1,2,3
 
             };
 
 
            var result1 = firstNumbers.Union(secondNumbers).ToList();
            var result2 = firstNumbers.Intersect(thressNumbers).ToList();
            var result3 = firstNumbers.Except(thressNumbers).ToList();
            Console.WriteLine("以下是并集的结果");
            result1.ForEach(x => Console.WriteLine(x));
 
            Console.WriteLine();
            Console.WriteLine("以下是交集的结果");
            result2.ForEach(x => Console.WriteLine(x));
 
            Console.WriteLine();
            Console.WriteLine("以下是差集的结果");
            result3.ForEach(x => Console.WriteLine(x));
            Console.WriteLine("以上是简单类型如:int string long。。。。。没有实现IEqualityComparer<T>接口");

原文地址:https://www.cnblogs.com/vaevvaev/p/7194729.html