• C# 对List取交集、差集、并集


    原文:https://www.cnblogs.com/Cein/p/11465737.html

    List<T>以string类型为例,实际应用中可换做其他类型:

    1:取交集

    复制代码
     // 取交集
            static void Intersection()
            {
                List<string> list1 = new List<string> { "AA", "BB", "CC", "EE", "GG" };
                List<string> list2 = new List<string> { "BB", "DD", "GG", "MM" };
                List<string> list3 = new List<string>();
                list3 = list1.Intersect(list2).ToList();
     
                Console.Write(list3.Count);  //交集的个数,如果个数为0,说明没有交集
                Console.WriteLine();
                foreach (var s in list3)      // 各个值
                {
                    Console.Write(s);
                    Console.WriteLine();
                }
            }
    复制代码

    结果:

    BB

    GG

    2:取差集

    复制代码
     // 取差集
            static void Exception()
            {
                List<string> list1 = new List<string> { "AA", "BB", "CC", "EE", "GG" };
                List<string> list2 = new List<string> { "BB", "DD", "GG", "MM" };
                List<string> list3 = new List<string>();
                list3 = list1.Except(list2).ToList();
     
                Console.Write(list3.Count);  //差集的个数,如果个数为0,说明list1中存在的值也全都存在于list2中
                Console.WriteLine();
                foreach (var s in list3)      // 各个值
                {
                    Console.Write(s);
                    Console.WriteLine();
                }
            }
    复制代码

    结果:

    AA

    CC

    EE

    如果把取差集代码中的
     list3 = list1.Except(list2).ToList();
    换成
     list3 = list2.Except(list1).ToList();

    结果如下:

    DD

    MM

    listA.Except(B).ToList();

    注:差集表示listA中哪些值是listB中所不存在的;

    3:取并集

    复制代码
    // 取并集
            static void Union()
            {
                List<string> list1 = new List<string> { "AA", "BB", "CC", "EE", "GG" };
                List<string> list2 = new List<string> { "BB", "DD", "GG", "MM" };
                List<string> list3 = new List<string>();
                list3 = list1.Union(list2).ToList();
     
                Console.Write(list3.Count);  //并集的个数,一般不会为0,除非list1和list2中的元素个数都为0
                Console.WriteLine();
                foreach (var s in list3)      // 各个值
                {
                    Console.Write(s);
                    Console.WriteLine();
                }
            }
    复制代码

    结果:

    AA

    BB

    CC

    EE

    GG

    DD

    MM

    复制代码
    如果把上面取并集代码中的
    list3 = list1.Union(list2).ToList();
    换成
    list3 = list1.Concat(list2).ToList();
    或
    list1.AddRange(list2);
    list3.AddRange(list1);
    则将会保留重复项
    复制代码

    结果如下:

    {AA, BB, CC, EE, GG, BB, DD, GG, MM }

  • 相关阅读:
    mysql 配置
    idea 学会看log文件
    ac自动机(tree+kmp模板)
    矩阵快速幂(纯数学递推)
    矩阵快速幂(queue递推)
    RMQ(连续相同最大值)
    dp(过河问题)
    bfs(火星撞地球)
    相同子序列集合
    图博弈
  • 原文地址:https://www.cnblogs.com/zhang1f/p/12902646.html
Copyright © 2020-2023  润新知