List的交并补集

前言


最近在專案中,剛好遇到這個需求,

需要比對兩個List,進行一些交集等操作,

在以前我們可能需要寫很多行來完成這些動作,

但現在我們只需要藉由LinQ就能輕鬆達到我們的目的囉!

 

實際演練


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

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

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

List B : { 4 , 3 , 9 }

1var intersectedList = list1.Intersect(list2);

結果 : { 3 , 9 }

 

判斷A和B是否有交集

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

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

List B : { 4 , 3 , 9 }

1var expectedList = list1.Except(list2);

結果 : { 1 , 2 , 5 }

 

判斷A和B是否有差集

 

 

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

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

List B : { 4 , 3 , 9 }

01public 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}

 

1var mergedList = list1.Merge(list2);

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

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

1bool isIntersected = list1.Intersect(list2).Count() > 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值