zoukankan      html  css  js  c++  java
  • 俄罗斯水手 [C#] 对List<T>取交集、连集及差集


    ※本文使用int為例,若為使用自訂之DataModel,需實作IEquatable<T>介面才能使用

    1.  取交集 (A和B都有)

    List A : { 1 , 2 , 3 , 5 , 9 }

    List B : { 4 , 3 , 9 }

    1 var intersectedList = list1.Intersect(list2);

    結果 : { 3 , 9 }

     

    判斷A和B是否有交集

     

    1 bool isIntersected = list1.Intersect(list2).Count() > 0

    2. 取差集 (A有,B沒有)

    List A : { 1 , 2 , 3 , 5 , 9 }

    List B : { 4 , 3 , 9 }

    1 var expectedList = list1.Except(list2);

    結果 : { 1 , 2 , 5 }

     

    判斷A和B是否有差集

     

    1 bool isExpected = list1.Expect(list2).Count() > 0

     

     

    3.  取聯集 (包含A和B)

    List A : { 1 , 2 , 3 , 5 , 9 }

    List B : { 4 , 3 , 9 }

    01 public static class ListExtensions
    02 {
    03     public static List<T> Merge<T>(this List<T> source, List<T> target)
    04     {
    05         List<T> mergedList = new List<T>(source);
    06  
    07         mergedList.AddRange(target.Except(source));
    08  
    09         return mergedList;
    10     }   
    11 }

     

     

    1 var mergedList = list1.Merge(list2);

    結果 : { 1 , 2 , 3 , 5 ,9 , 4 }

    ※ 6/15補充:感謝蹂躪大大提醒,LinQ已有內建方法Union可取聯集囉!

  • 相关阅读:
    Linux shell(3)
    Linux shell 编写(2)
    Linux shell 编写(1)
    团队冲刺(一)
    峦码团队任务表
    电梯演讲&界面展示说明
    第一次小组会议——NABCD讨论
    开发项目&团队介绍
    Linux中查看各文件夹大小命令:du -h --max-depth=1
    shell脚本[] [[]] -n -z 的含义解析
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/6726055.html
Copyright © 2011-2022 走看看