LINQ中交集、并集、差集、去重(十四)

Sample Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> ListA = new List<int>() { 1, 2, 3, 3, 4, 5, 6, 7 };
            List<int> ListB = new List<int>() { 6, 7, 8, 7 };
            List<int> ListDistinct = new List<int>();
            List<int> ListExcept = new List<int>();
            List<int> ListUnion = new List<int>();
            List<int> ListIntersect = new List<int>();
            //1. 去重: 去除重复数据
            ListDistinct = ListA.Distinct().ToList(); //1, 2, 3, 4, 5, 6, 7

            //2. 差集: 在集合A中排除A和B公共部分,剩下集合A的元素就是A的差集,如果剩下的元素有重复,则自动去重
            ListExcept = ListA.Except(ListB).ToList(); //: 1, 2, 3, 4, 5 

            //3. 并集: 集合A和B所有元素组合成新集合并去重
            ListUnion = ListA.Union(ListB).ToList();  //1, 2, 3, 4, 5, 6, 7, 8

            //4. 交集:集合A和集合B元素的公共元素组成新集合并去重
            ListIntersect = ListA.Intersect(ListB).ToList(); //6, 7
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/LuckyZLi/p/12742746.html