zoukankan      html  css  js  c++  java
  • C# 对List<T>取交集、连集及差集

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

    需要比對兩個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     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可取聯集囉!

    結語


    使用Linq就可以輕鬆完成List的比對,

    如果有任何問題歡迎大家一起討論囉 :)

    转载于:http://www.cnblogs.com/liguanghui/archive/2011/11/09/2242309.html

    在开发过程中.数组和集合的处理是最让我们担心.一般会用for or foreach 来处理一些操作.这里介绍一些常用的集合跟数组的操作函数. 

    首先举例2个集合A,B. 

     List<int> listA = new List<int> {1,2,3,5,7,9};

     List<int> listB = new List<int> {13,4,17,29,2};
     listA.AddRange(listB );把集合A.B合并
     List<int> Result = listA.Union(listB).ToList<int>();          //剔除重复项 
     List<int> Result = listA.Concat(listB).ToList<int>();        //保留重复项

     listA.BinarySearch("1");//判断集合中是否包含某个值.如果包含则返回0

    在举例两个数组

      int[] i=new int[]{1,2};
      int[] j=new int[]{2,3};
      List<int> r = new List<int>();  

      r.AddRange(i);

      r.AddRange(j);

      int[] c = r.ToArray(); 合并数组

      int[] x=i.Union(j).ToArray<int>(); //剔除重复项 

      int[] x=i.Concat(j).ToArray<int>(); //保留重复项

      int n = Array.BinarySearch(i,3);//判断数组中是否包含某个值.如果包含则返回0

    本文转自:http://blog.csdn.net/lingxyd_0/article/details/20877721

  • 相关阅读:
    终于开通了
    <input>表单元素readonly时光标仍然可见
    关于字体
    SSI架构中get***方法潜在调用
    为uploads文件夹瘦身
    在JSP里使用CKEditor和CKFinder
    centos5.5上搭建svn服务器
    多文件上传
    属性化ATL,DCOM,SIM,IID
    BSTR转换成char*
  • 原文地址:https://www.cnblogs.com/dazhuangtage/p/5314188.html
Copyright © 2011-2022 走看看