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. macbook pro 突破校园网inode客户端限制分享网络

    [原创] 环境: 1. macbook pro (retina) 2. mac os x 10.9 3. H3C inode for mac 7.0 分享方法: 1.打开inode联网. 2.打开设置 ...

  2. 11、手把手教你Extjs5(十一)模块界面的总体设计

    上一节中设计了一些模块自定义中用到的要素,为了直观起见,这一节先建立一个模块的主界面.看过我 模块管理常规功能自定义系统的设计与实现 博客的人应该会有所了解了.一个模块的主界面是一个Grid,在其上方 ...

  3. 关于iOS开发中info.plist文件的解读

    我们建立一个工程后,会在Supporting files下面看到一个"工程名-Info.plist"的文件,这个是对工程做一些运行期配置的文件,很重要,不能删除.  下面就对其ke ...

  4. iOS 之 手势

    手势操作,有一个总的抽象类UIGestureRecognizer,用于检测设备的所有手势.其下有多个子类: 拍击UITapGestureRecognizer (任意次数的拍击) 向里或向外捏UIPin ...

  5. Python3基础 pop() 删除 键为指定值的项

    镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...

  6. 【腾讯优测干货分享】微信小程序之自动化亲密接触

    本文来自于腾讯优测公众号(wxutest),未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/HcPakz5CV1SHnu-U8n85pw 导语 山雨欲来风满楼,最 ...

  7. UVa 10716 - Evil Straw Warts Live

    题目大意:给一个字符串,判断是否能通过交换字母构成回文,如果能,计算所需的最小交换次数. 如果字符串中出现奇数次的字母的个数>1,则不能构成回文.然后...就没思路了...看网上说用贪心的思想先 ...

  8. 八 Appium常用方法介绍

    由于appium是扩展了Webdriver协议,所以可以使用webdriver提供的方法,比如在处理webview页面,完全可以使用webdriver中的方法.当然在原生应用中,也可以使用. 1.元素 ...

  9. win7(windows 7)系统下安装SQL2005(SQL Server 2005)图文教程——转载

    操作系统:Microsoft Windows 7 旗舰版(32位) 数据库版本:SQL Server 2005 简体中文开发板 数据库下载链接:http://pan.baidu.com/share/l ...

  10. Intent的属性及Intent-filter配置——Action、Category属性与intent-filter属性

    Intent的Action.Category属性都是一个普通的字符串,其中Action代表该Intent所要完成的一个抽象“动作”,而Category则用于为Action增加额外的附加列别的信息.通常 ...