LINQ左连接+默认如果空+匿名类型+组由

本文关键字:类型 组由 如果 连接 默认 LINQ | 更新日期: 2023-09-27 18:03:39

我想知道什么是给定问题的最佳解决方案,简化如下:

  1. 我有两个本地存储的sql表,我想加入(左连接)默认如果空属性,然后我需要组这些数据

  2. 我不想在访问obj之前检查(obj == null)。如果给定行

  3. 的连接没有成功,将抛出错误。

数据
LeftTable    RightTable    OUTPUT
 A B C        A B Z         A  B  C  Z
 1 1 1        1 1 5         1  1  1  5
 1 2 2        1 2 6         1  2  2  6
 5 6 7                      5  6  7 null

代码
var RightTable = from row in Source
                 where row.X > 10
                 select new {        // anonymous type that I want to keep
                    A = row.AAA,
                    B = row.BBB,
                    Z = row.ZZZ
                 };
var test = from left in LeftTable
           from right in RightTable
             .Where(right => right.A == left.A
                && right.B == left.B )
             .DefaultIfEmpty( /* XXXXX */ )   //<-- this line is interesting
           group left by new {
             left.A
             left.B
             left.C
             right.Z  //<-- this will throw null exception error
           } into g     //  but I don't want to change it to 
           select g;    //  Z = (right != null) ? right.Z : (string) null

问题:

我可以填充一个参数在DefaultIfEmpty与任何东西,我可以动态地从这段代码?

我知道我可以像下面这样创建一个helper类型,并替换右表选择中的匿名类型,并在默认情况下使用它,如果为空,如:

DefaultIfEmpty(new Helper())

但是我不想这样做,因为我必须在现实生活中处理20,30多个列。

public class Helper {
    public string A,
    public string B,
    public string C
}

如果你读到这里,非常感谢你的时间。希望在这里得到一些解决方案。谢谢。

LINQ左连接+默认如果空+匿名类型+组由

我认为code说明了一切:

var LeftTable = new[]
        {
            new { A = 1, B=1, C=1 },
            new { A = 1, B=2, C=2 },
            new { A = 5, B=6, C=7 }
        }
        .ToList();

        var RightTable = new[]
        {
            new { A = 1, B=1, Z=5 },
            new { A = 1, B=2, Z=6 }
        }
        .ToList();

        var query = (from left in LeftTable
                     join right in RightTable
                        on new { left.A, left.B } equals new { right.A, right.B }
                        into JoinedList
                     from right in JoinedList.DefaultIfEmpty(new { A = 0, B = 0, Z = 0 })
                     group left by new
                     {
                         left.A,
                         left.B,
                         left.C,
                         right.Z
                     } into g
                     select g)
                    .ToList();

我遇到了和你一样的问题,我必须找到一种方法,想到了这样的事情(非常简化的例子):

var toReturn = from left in bd.leftys
               join rights in myAnonimousGroupedList on left.Id equals rights.leftId into joinings
               from right in joinings.DefaultIfEmpty()
               select new {
                   left.A
                   left.B
                   left.C
                   // Z = right != null ? right.Z : 0
                   Z = joinings.Any() ? right.Z : 0 // see what i did here?
               };