0

我正在尝试在 LINQ 中创建外连接语句,但运气不佳。我知道执行外部连接需要两个步骤:

(1)将join转换为group join with into

(2) 如果连接的结果集为空,则在组上使用 DefaultIfEmpty() 生成您期望的空值。

我一直以这段代码为例:

var query = (from p in dc.GetTable<Person>()
join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
from addresses in tempAddresses.DefaultIfEmpty()
select new { p.FirstName, p.LastName, addresses.State });

所以我试着这样做:

var outerJoin =

    from h in resultHours         
    join u in results on h.Key equals u.Key into outer
    from dictionary in outer.DefaultIfEmpty()
    select new { 

问题是智能感知无法识别 select new {} 语句中的任何内容。我试过你。和 h.,甚至是字典。

我可能遇到的问题是我正在尝试外部加入两个字典。它似乎不喜欢那样,虽然这是我被告知我需要做的。我显然做错了什么或不理解某事。

我需要将字典 results.Unit 与字典 resultHours.Hours 一起加入,因为我的输出在某些条件下缺少 unitId 字段。进行外部连接应该可以解决这个问题。

这是结果的代码:

var results = 

    (from v in VDimUnit     
        join vf in VFactEnergyAllocation on v.UnitKey equals vf.UnitKey
        join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
        join vt in VDimTime on vf.TimeKey equals vt.TimeKey 
    where typeCodes.Contains(vd.GadsEventTypeCode)
    && vt.YearNum >= (year - 3) && vt.YearNum <= year       
    group vf by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity, 
    vt.MonthNum} into groupItem     
    select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
    groupItem.Key.MonthNum, PO_HRS = groupItem.Sum(
    x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
            UO_HRS = groupItem.Sum(x=> (float)x.AllocatedEnergyMwh / groupItem.Key.NetDependableCapacity),
        Unit = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key, x=> x);

这是 resultHours 的代码:

var resultHours = 

    (from vt in VDimTime
        join vf in VFactEnergyAllocation on vt.TimeKey equals vf.TimeKey         
        join vd in VDimGadsEvent on vf.GadsEventKey equals vd.GadsEventKey
        join v in VDimUnit on vf.UnitKey equals v.UnitKey       

    group vt by new {v.PlantId, v.PhysicalUnitId, v.NetDependableCapacity, v.NetMaximumCapacity, 
        vt.MonthNum} into groupItem
    select new {groupItem.Key.PlantId, groupItem.Key.PhysicalUnitId, groupItem.Key.NetMaximumCapacity,
        Hours = groupItem.Count(), groupItem.Key}).ToDictionary(x=> x.Key.ToString(), x=> x.Hours); 

这就是我目前的输出方式。在我弄清楚如何进行外部连接后它会改变。

var finalResults = 

    (from r in results
    orderby r.Key.MonthNum, r.Key.PlantId, r.Key.PhysicalUnitId
    select new {Site = r.Key.PlantId, Unit = r.Key.PhysicalUnitId, r.Key.MonthNum, Numerator = r.Value.PO_HRS, Denominator = 
        resultHours[r.Key.ToString()], Weight = r.Key.NetMaximumCapacity, Data_Indicator = DATA_INDICATOR, 
        Budgeted = budgetedPlannedOutageHrs, Industry_Benchmark = INDUSTRY_BENCHMARK, Comments = comments, 
        Executive_Comments = executiveComments, Fleet_Exec_Comments = fleetExecComments});

我不知所措。我发现的 LINQ 外连接示例显然不适用于连接字典。

4

0 回答 0