convert this LINQ expression into Lambda

后端 未结 7 885
春和景丽
春和景丽 2020-11-29 07:56

Guys, I have a hard time converting this below linq expression(left join implementation) to lambda expression (for learning).

var result = from g in groc         


        
7条回答
  •  一整个雨季
    2020-11-29 08:25

    I usually use ReSharper to help me convert things to method chains and lambda's, which helps me go back and forth fairly easy.

        var result = from g in grocery
                     join f in fruit on g.fruitId equals f.fruitId into tempFruit
                     join v in veggie on g.vegid equals v.vegid into tempVegg
                     from joinedFruit in tempFruit.DefaultIfEmpty()
                     from joinedVegg in tempVegg.DefaultIfEmpty()
                     select new { g.fruitId, g.vegid, fname = ((joinedFruit == null) ? string.Empty : joinedFruit.fname), vname = ((joinedVegg == null) ? string.Empty : joinedVegg.vname) };
    

    And then using ReSharper's option of convert LINQ to method chain equals the following:

            var result =grocery .GroupJoin(fruit, g => g.fruitId, f => f.fruitId, (g, tempFruit) => new {g, tempFruit})
                                .GroupJoin(veggie, @t => @t.g.vegid, v => v.vegid, (@t, tempVegg) => new {@t, tempVegg})
                                .SelectMany(@t => @t.@t.tempFruit.DefaultIfEmpty(), (@t, joinedFruit) => new {@t, joinedFruit})
                                .SelectMany(@t => @t.@t.tempVegg.DefaultIfEmpty(),(@t, joinedVegg) =>
                                    new
                                        {
                                            @t.@t.@t.g.fruitId,
                                            @t.@t.@t.g.vegid,
                                            fname = ((@t.joinedFruit == null) ? string.Empty : @t.joinedFruit.fname),
                                            vname = ((joinedVegg == null) ? string.Empty : joinedVegg.vname)
                                        });
    

    Granted the output is less then desirable, but It at least helps in starting somewhere on understanding the syntax.

提交回复
热议问题