[轉貼] LinQ 對List 取交集、聯集及差集

 

出處:http://www.dotblogs.com.tw/kirkchen/archive/2010/06/12/15836.aspx

前言


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

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

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

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

 

實際演練


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

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

List list1 = new List { 1, 2, 3, 5, 9 };
List list2 = new List { 4, 3, 9 };

var intersectedList = list1.Intersect(list2);


結果 : { 3 , 9 }

判斷A和B是否有交集

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

 

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

List list1 = new List { 1, 2, 3, 5, 9 };
List list2 = new List { 4, 3, 9 };

var expectedList = list1.Except(list2);


結果 : { 1 , 2 , 5 }

判斷A和B是否有差集

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

 

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

List list1 = new List { 1, 2, 3, 5, 9 };
List list2 = new List { 4, 3, 9 };

var unionList = list1.Union(list2);


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

判斷A和B是否有聯集

bool isUnioned = list1.Union(list2).Count() > 0

 

採用自訂擴充方法取聯集

public static class ListExtensions
{
    public static List Merge (this List source, List target)
    {
        List mergedList = new List (source);

        mergedList.AddRange(target.Except(source));
        return mergedList;
    }   
}

var mergedList = list1.Merge(list2);

留言

這個網誌中的熱門文章

TeknoParrot 模擬器介紹,俗稱《鸚鵡模擬器》

[轉貼] ASP.NET傳遞參數給Crystal Report做Export或Print的動作

[轉貼] Server 端Post資料到 .ashx