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可取聯集囉!

  • 相关阅读:
    idea的使用和安装破解 2019.2
    get请求和post请求的区别
    MySQL-事务
    MySQL-mysql的查询练习
    MySQL-mysql的多表查询
    CodeForces
    2018宁夏邀请赛网赛 I. Reversion Count(java练习题)
    HDU
    Codeforces Round #479 (Div. 3)解题报告
    nyoj 1274信道安全 第九届河南省赛(SPFA)
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/6726055.html
Copyright © 2011-2022 走看看