LINQ左外连接的条件大于和小于日期

问题描述 投票:0回答:2

我一直在努力解决这个问题,并且无法找到具有基于日期的多个条件的LINQ外连接的语法。我一直在研究GroupJoin语法,但这只是让你比较一个字段值(通常是ID)。

我想测试父表是否有一个日期(例如“UpdateDate”),该日期属于子表中定义的多个值(例如“StartDate”和“EndDate”)。如果父日期符合条件,请从子表中拉出一列或两列。如果不是,那么子表中的那些列应该为null(经典的左连接东西)。

我不认为查询语法会起作用,因为它只识别equijoins。

有没有办法在LINQ中使用Lambda语法执行此操作?我一直在尝试使用“SelectMany”和“DefaultIfEmpty”的某种组合,但一直试图定义连接。

linq conditional left-join
2个回答
0
投票

在linq中执行此操作的方法:

var q = from a in TableA
        from b in TableB.where(x => a.Date > x.StartDate && a.Date < x.EndDate).DefaultIfEmpty()
        select {...}

0
投票

使用ResultSelector的参数Queryable.GroupJoin来选择你想要的:

var result = dbContext.Parents.GroupJoin(dbContext.Children,

    // outer and inner key Selectors:
    parent => parent.Id,       // from every parent take the primary key
    child => child.ParentId,   // from every child take the foreign key to parent

    // ResultSelector: take the parent and all his children to make one new object
    (parent, children) => new
    {
        // Select only the Parent properties you actually plan to use:
        Id = parent.Id,
        Name = parent.Name,
        ...

        Children = children.Select(child => new
        {
            // select only Child properties you plan to use:
            Id = child.Id,
            // No need: you know the value: ParentId = child.ParentId,
            ...

“如果父日期符合条件,请从子表中提取一两列,否则子表中的那些列应为null”

            SpecialColumnA = (parent.BirthDay.Year < 2000) ?? child.BirthDay : null,
            SpecialColumnB = (parent.Name == "Kennedy" ?? child.Name : null,
    });

如果许多列的条件相同,请考虑仅检查一次:

        SpecialColumns = (parent.Birthday.Year >= 2000) ? null :
            // else fill the special columns:
            new
            {
                Name = child.Name,
                SomeWeirdProperty = parent.Id + child.Id,
                ...
            },
    }); 
© www.soinside.com 2019 - 2024. All rights reserved.