Linq将两个班级合并为三个班级?

时间:2012-12-19 22:30:14

标签: c# linq

我正在尝试将2个类合并到日期属性的第三个类中,以便绑定到我已设置的图形。

public class Last30DaysHours
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
    public float LostHours { get; set; }
}

public class MachineHours
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
}

public class GraphLast30Days
{
    public DateTime Date { get; set; }
    public float Hours { get; set; }
    public float LostHours { get; set; }
    public float SelectedMachine { get; set; }
}

到目前为止,我有这个几乎编译的linq语句。 当前法规的错误是"' x'在当前上下文中不存在"。

我知道这意味着什么,但我不知道如何在声明中使其可访问。

IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect = _last30DaysMachineHours
            .Select(p => (_last30Days
                            .Where(x => x.Date == p.Date)  <= 
                            (new GraphLast30Days { 
                                                    Date = x.Date, 
                                                    Hours = x.Hours, 
                                                    LostHours = x.LostHours, 
                                                    SelectedMachine = p.Hours 
                                                  })));             

我的问题是如何通过声明的后半部分使x可访问,或者获得相同结果的更好的声明是什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

你不会按日期使用加入加入你的收藏(不确定我得到了正确的proeprties,但你明白了):

IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect = 
        from machineHours in _last30DaysMachineHours
        join last30 in _last30Days on machineHours.Date equals last30.Date
        select
        new GraphLast30Days { 
            Date = machineHours.Date, 
            Hours = machineHours.Hours, 
            LostHours = last30.LostHours, 
            SelectedMachine = machineHours.Hours
            };

或使用其他语法:

    var result = _last30DaysMachineHours.Join(_last30Days, graph => graph.Date, last30 => last30.Date, 
                                             (graph, last30) => new GraphLast30Days
                                                                {
                                                                        Date            = graph.Date,
                                                                        Hours           = graph.Hours,
                                                                        LostHours       = last30.LostHours,
                                                                        SelectedMachine = graph.Hours
                                                                });

如果你不想过滤丢失的值,你需要做左连接:

IEnumerable<GraphLast30Days> last30DaysMachineHoursSelect =
    from last30 in _last30Days
    from machineHours in _last30DaysMachineHours.Where (h => h.Date == last30.Date).DefaultIfEmpty()
    select
    new GraphLast30Days { 
        Date = last30.Date, 
        Hours = last30.Hours, 
        LostHours = last30.LostHours, 
        SelectedMachine = machineHours == null ? 0 : machineHours.Hours
        }