C# 對List取交集、連集及差集

來源:互聯網
上載者:User

轉載於:http://www.cnblogs.com/shuibin/archive/2012/04/19/2457867.html

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

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

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

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

  實際演練


※本文使用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     pub

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.