Linq 集合操作

演示代码

两个对象一个是Person,一个Address, AddressId是外键,

public class Person

{

public string ID { get; set; }

public string Name { get; set; }

public int Age { get; set; }

public double Salary { get; set; }

public DateTime Born { get; set; }

public int IdAddress { get; set; }

}

public class Address

{

public int IdAddress { get; set; }

public string Street { get; set; }

public int Num { get; set; }

public string City { get; set; }

}

  

测试数据如下

Person类

Address类

下面我会用7个方式实现7中集合操作

  1. INNER JOIN 内链接
  2. LEFT JOIN 左连接
  3. RIGHT JOIN 右链接
  4. FULL OUTER JOIN 所有
  5. LEFT JOIN EXCLUDING INNER JOIN 左空
  6. RIGHT JOIN EXCLUDING INNER JOIN 右空
  7. FULL OUTER JOIN EXCLUDING INNER JOIN ??

    学校数学没学好不知道专业术语!哈哈

    INNER JOIN

    最常用的方法,两表关联查询

    标准Linq语法

    var result = from p in Person.BuiltPersons()
    
    join a in Address.BuiltAddresses()
    
    on p.IdAddress equals a.IdAddress
    
    select new
    
         {
    
    Name = a.MyPerson.Name,
    
    Age = a.MyPerson.Age,
    
    PersonIdAddress = a.MyPerson.IdAddress,
    
    AddressIdAddress = a.MyAddress.IdAddress,
    
    Street = a.MyAddress.Street
    
         };
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().Join( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = a.MyPerson.Name,
    
    Age = a.MyPerson.Age,
    
    PersonIdAddress = a.MyPerson.IdAddress,
    
    AddressIdAddress = a.MyAddress.IdAddress,
    
    Street = a.MyAddress.Street
    
    });
    

      

    Lambda表达式主要有5部分

  8. Is the main Collection. 
  9. Is the inner Collection.
  10. Is the PK.
  11. Is the FK.
  12. Is the type for the result collection. 

    查询结果如下

    LEFT JOIN

    新增一个LeftJoin的扩展方法

    public static IEnumerable<TResult>
    
        LeftJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    IEnumerable<TResult> _result = Enumerable.Empty<TResult>();
    
    _result = from s in source
    
    join i in inner
    
    on pk(s) equals fk(i) into joinData
    
    from left in joinData.DefaultIfEmpty()
    
    select result(s, left);
    
    return _result;
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().LeftJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = a.MyPerson.Name,
    
    Age = a.MyPerson.Age,
    
    PersonIdAddress = a.MyPerson.IdAddress,
    
    AddressIdAddress = (a.MyAddress != null ? a.MyAddress.IdAddress : -1),
    
                Street = (a.MyAddress != null ? a.MyAddress.Street : "Null-Value")
    
    });
    

      

    注意:如果address为空Null需要做一个替换,否则会报错

    查询结果如下

    RIGHT JOIN

    Extension Method:

    public static IEnumerable<TResult>
    
        RightJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    IEnumerable<TResult> _result = Enumerable.Empty<TResult>();
    
    _result = from i in inner
    
    join s in source
    
    on fk(i) equals pk(s) into joinData
    
    from right in joinData.DefaultIfEmpty()
    
    select result(right, i);
    
    return _result;
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().RightJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = (a.MyPerson != null ? a.MyPerson.Name : "Null-Value"),
    
    Age = (a.MyPerson != null ? a.MyPerson.Age : -1),
    
    PersonIdAddress = (a.MyPerson != null ? a.MyPerson.IdAddress : -1),
    
    AddressIdAddress = a.MyAddress.IdAddress,
    
    Street = a.MyAddress.Street
    
    });
    

      

    查询结果如下

    FULL OUTER JOIN

    Extension Method:

    public static IEnumerable<TResult>
    
        FullOuterJoinJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    var left = source.LeftJoin(inner, pk, fk, result).ToList();
    
    var right = source.RightJoin(inner, pk, fk, result).ToList();
    
    return left.Union(right);
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().FullOuterJoinJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = (a.MyPerson != null ? a.MyPerson.Name : "Null-Value"),
    
    Age = (a.MyPerson != null ? a.MyPerson.Age : -1),
    
    PersonIdAddress = (a.MyPerson != null ? a.MyPerson.IdAddress : -1),
    
    AddressIdAddress = (a.MyAddress != null ? a.MyAddress.IdAddress : -1),
    
    Street = (a.MyAddress != null ? a.MyAddress.Street : "Null-Value")
    
    });
    

      

    注意:每个对象都需要验证Null

    查询结果如下

    LEFT EXCLUDING JOIN

    Extension Method:

    public static IEnumerable<TResult>
    
        LeftExcludingJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    IEnumerable<TResult> _result = Enumerable.Empty<TResult>();
    
    _result = from s in source
    
    join i in inner
    
    on pk(s) equals fk(i) into joinData
    
    from left in joinData.DefaultIfEmpty()
    
    where left == null
    
    select result(s, left);
    
    return _result;
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().LeftExcludingJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = a.MyPerson.Name,
    
    Age = a.MyPerson.Age,
    
    PersonIdAddress = a.MyPerson.IdAddress,
    
    AddressIdAddress = (a.MyAddress != null ? a.MyAddress.IdAddress : -1),
    
    Street = (a.MyAddress != null ? a.MyAddress.Street : "Null-Value")
    
    });
    

      

    查询结果如下

    RIGHT EXCLUDING JOIN

    Extension Method:

    public static IEnumerable<TResult>
    
    RightExcludingJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    IEnumerable<TResult> _result = Enumerable.Empty<TResult>();
    
    _result = from i in inner
    
    join s in source
    
    on fk(i) equals pk(s) into joinData
    
    from right in joinData.DefaultIfEmpty()
    
    where right == null
    
    select result(right, i);
    
    return _result;
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().RightExcludingJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = (a.MyPerson != null ? a.MyPerson.Name : "Null-Value"),
    
    Age = (a.MyPerson != null ? a.MyPerson.Age : -1),
    
    PersonIdAddress = (a.MyPerson != null ? a.MyPerson.IdAddress : -1),
    
    AddressIdAddress = a.MyAddress.IdAddress,
    
    Street = a.MyAddress.Street
    
    });
    

      

    查询结果

    FULL OUTER EXCLUDING JOIN

    Extension Method:

    public static IEnumerable<TResult>
    
    FulltExcludingJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source,
    
    IEnumerable<TInner> inner,
    
    Func<TSource, TKey> pk,
    
    Func<TInner, TKey> fk,
    
    Func<TSource, TInner, TResult> result)
    
    {
    
    var left = source.LeftExcludingJoin(inner, pk, fk, result).ToList();
    
    var right = source.RightExcludingJoin(inner, pk, fk, result).ToList();
    
    return left.Union(right);
    
    }
    

      

    Lambda Expression:

    var resultJoint = Person.BuiltPersons().FulltExcludingJoin( /// Source Collection
    
    Address.BuiltAddresses(), /// Inner Collection
    
    p => p.IdAddress, /// PK
    
    a => a.IdAddress, /// FK
    
    (p, a) => new { MyPerson = p, MyAddress = a }) /// Result Collection
    
    .Select(a => new
    
    {
    
    Name = (a.MyPerson != null ? a.MyPerson.Name : "Null-Value"),
    
    Age = (a.MyPerson != null ? a.MyPerson.Age : -1),
    
    PersonIdAddress = (a.MyPerson != null ? a.MyPerson.IdAddress : -1),
    
    AddressIdAddress = (a.MyAddress != null ? a.MyAddress.IdAddress : -1),
    
    Street = (a.MyAddress != null ? a.MyAddress.Street : "Null-Value")
    
    });
    

      

    查询结果

Linq 集合操作的更多相关文章

  1. Linq集合操作之Intersect,Except,Union源码分析

    Linq集合操作之Intersect,Except,Union源码分析 linq的集合运算 常见的集合运算有哪些? 这三个扩展方法在我们实际使用中用的还是非常多的,而且这里还涉及到了“复杂度” 无算法 ...

  2. C#LINQ集合操作

    LINQ的集合运算 List<int> lstOne = new List<int>() { 1, 55, 223, 25 }; List<int> lstTwo ...

  3. Linq聚合操作之Aggregate,Count,Sum,Distinct源码分析

    Linq聚合操作之Aggregate,Count,Sum,Distinct源码分析 一:Linq的聚合运算 1. 常见的聚合运算:Aggregate,Count, Sum, Distinct,Max, ...

  4. Linq生成操作之DefautIfEmpty,Empty,Range,Repeat源码分析

    Linq生成操作之DefautIfEmpty,Empty,Range,Repeat源码分析 Linq的四种生成运算 DefautIfEmpty,Empty,Range,Repeat 也就是给我们初始化 ...

  5. Linq转换操作之OfType,Cast,AsEnumerable,ToLookup源码分析

    Linq转换操作之OfType,Cast,AsEnumerable,ToLookup源码分析 一:Tolookup 1. 从方法的注解上可以看到,ToLookup也是一个k,v的形式,那么问题来了,它 ...

  6. Linq转换操作之ToArray,ToList,ToDictionary源码分析

    Linq转换操作之ToArray,ToList,ToDictionary源码分析 一:linq中的转换运算符 1. ToArray 我们经常用在linq查询上吧. linq只能运用在IEnumerab ...

  7. 函数式Android编程(II):Kotlin语言的集合操作

    原文标题:Functional Android (II): Collection operations in Kotlin 原文链接:http://antonioleiva.com/collectio ...

  8. JAVASE02-Unit05: 集合操作 —— 查找表

    Unit05: 集合操作 -- 查找表 使用该类测试自定义元素的集合排序 package day05; /** * 使用该类测试自定义元素的集合排序 * @author adminitartor * ...

  9. JAVASE02-Unit04: 集合框架 、 集合操作 —— 线性表

    Unit04: 集合框架 . 集合操作 -- 线性表 操作集合元素相关方法 package day04; import java.util.ArrayList; import java.util.Co ...

随机推荐

  1. kafka第四篇--快速入门(如何使用kafka)

    Quick Start Step 1: Download the code Download the 0.8 release. > tar xzf kafka-<VERSION>.t ...

  2. HUST 1371 Emergency relief

    状态压缩. 每一个人所需的物品对应一个数字,统计一个每个数字有几个.每一种提供物品的状态也对应一个数字,然后暴力判断. #include<cstdio> #include<cstri ...

  3. 单应性(homography)变换的推导

    矩阵的一个重要作用是将空间中的点变换到另一个空间中.这个作用在国内的<线性代数>教学中基本没有介绍.要能形像地理解这一作用,比较直观的方法就是图像变换,图像变换的方法很多,单应性变换是其中 ...

  4. 现在开始使用 ES6

    ECMAScript已经在2015年6月正式发布了,这门语言一直保持稳定快速的发展而且新功能也在慢慢被现在主流的 JavaScript 引擎所接受.不过要想在浏览器端或者 Node 端直接运行 ES6 ...

  5. axis2开发实例(一)

    主要参考<axis2之webservice新手超详细教程http://wenku.baidu.com/view/6eae036d011ca300a6c390a4.html> <axi ...

  6. 《数据结构与算法分析:C语言描述》读书笔记------练习1.1 求第K大的数

    求一组N个数中的第k个最大者,设k=N/2. import java.util.Random; public class K_Max { /** * @param args */ //求第K大的数,保 ...

  7. STM8S awu及看门狗IWDG WWDG应用(转)

    源:STM8S awu及看门狗IWDG WWDG应用 AWU的应用(用库函数完成的) //切记要开启中断 且在中断函数中 AWU_GetFlagStatus(); 来清除中断 void AWU_SET ...

  8. 理解javascript函数的重载

        javascript其实是不支持重载的,这篇文章会和java语言函数的重载对比来加深对javascript函数重载的理解.       以下我会假设读者不了解什么是重载所以会有一些很基础的概念 ...

  9. CSS排序工具csscomb

    一. css写久了以后感觉需要按照某种规则或者说顺序来,便于开发和维护.O(∩_∩)O哈哈~ 找到一个 http://csscomb.com/ CSS排序总结: 1. 对css样式排序; 2. 按样式 ...

  10. JAVA判断32位还是64位,调用不同的DLL(转)

    源:JAVA判断32位还是64位,调用不同的DLL 通过获取sun.arch.data.model可判断是32还是64的JAVA 将32或者64位的DLL放不同的目录,实现自适应调用DLL Prope ...