• 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
            }
        }
    }
  • 相关阅读:
    3294 [SCOI2016]背单词
    P4551 最长异或路径
    BZOJ 4260: Codechef REBXOR
    P2322 [HNOI2006]最短母串问题
    P2444 [POI2000]病毒
    P3121 [USACO15FEB]审查(黄金)Censoring (Gold)
    BZOJ 3942: [Usaco2015 Feb]Censoring
    EZOJ #77
    EZOJ #73
    547D Mike and Fish
  • 原文地址:https://www.cnblogs.com/LuckyZLi/p/12742746.html
Copyright © 2020-2023  润新知