LinQ操作List<>对象

转载于: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是否有交集

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

  

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

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

List B : { 4 , 3 , 9 }

var expectedList = list1.Except(list2);

  結果 : { 1 , 2 , 5 }

 

判断A和B是否有差集 

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

   

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

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

List B : { 4 , 3 , 9 }

public static class ListExtensions

{

    public static List<T>  Merge<T>(this List<T> source, List<T> target)
    {
        List<T> mergedList = new List<T>(source);
        mergedList.AddRange(target.Except(source));
       return mergedList;

    }   

}

var  mergedList = list1.Merge(list2);

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

 

結語


使用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

 

转载于:https://www.cnblogs.com/wslm/p/4354292.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值