linq join

    数据准备:
    List<dynamic> ls1=new List<dynamic>{
        new {Id = 1,Name = "张三"},
        new {Id = 2,Name = "李四"},
        new {Id = 3,Name = "王五"},
        new {Id = 4,Name = "赵六"}
    };
    List<dynamic> ls2=new List<dynamic>{
        new {Name = "张三", Subject="语文", Score=60},
        new {Name = "张三", Subject="数学", Score=70},
        new {Name = "张三", Subject="外语", Score=80},
        new {Name = "李四", Subject="语文", Score=85},
        new {Name = "王五", Subject="语文", Score=69}
    };

Join

Inner Join

    var ls = from x in ls1
             join y in ls2 on x.Name equals y.Name
             select new {
                 Id = x.Id,
                 Name = x.Name,
                 Subject = y.Subject,
                 Score = y.Score
             };
    // or 
    var ls = ls1.Join(ls2, x=>x.Name, y=>y.Name, (x,y)=>new {
                 Id = x.Id,
                 Name = x.Name,
                 Subject = y.Subject,
                 Score = y.Score
             });

Left Outer Join

    var ls = from x in ls1
             join y in ls2 on x.Name equals y.Name into g
             from z in g.DefaultIfEmpty()
             select new {
                 Id = x.Id,
                 Name = x.Name,
                 Subject = z?.Subject,
                 Score = z?.Score
             };

GroupJoin

    var ls = from x in ls2
             group x by x.Subject into g
             select new {
                 Subject = g.Key,
                 MaxScore = g.Max(x=>x.Score)
             };

Order By

    var ls = from x in ls2
             orderby x.Subject,x.Score descending
             select x
posted @ 2018-08-24 09:39  上飘的枫叶  阅读(964)  评论(0编辑  收藏  举报