LINQ - 加入两个DataTable,乘以3列,然后得到总和

我有两个DataTable .

我需要加入它们,将三列再乘以另外三列,然后获得这两列的总和 . 如果它是纯SQL,则不会有group by子句,只有join和SUM . 这是我到目前为止所拥有的,但我得到“查询正文必须以select子句或group子句结束”,即使我以select子句结束(我试图选择我的总数到变量)

decimal weight = 0;
        decimal volume = 0;

            var results = from line in xferLinesTable.AsEnumerable()
                          join invmast in inv_mast.AsEnumerable()
                            on line.Field<int>("inv_mast_uid") equals invmast.Field<int>("inv_mast_uid")

                          let extended_weight = line.Field<decimal>("quantity_requested") * line.Field<decimal>("unit_size") * invmast.Field<decimal>("net_weight")
                          let extended_volume = line.Field<decimal>("quantity_requested") * line.Field<decimal>("unit_size") * invmast.Field<decimal>("cube")
                          into lines

                          select weight = lines.Sum(w => w.extended_weight), volume = lines.Sum(v => v.extended_volume);

我哪里错了? TIA .

回答(2)

3 years ago

您可以尝试使用匿名类型 . 像这样的东西:

select new {weight = lines.Sum(w => w.extended_weight), volume = lines.Sum(v => v.extended_volume)};

仔细看看你的代码 . 您使用 into 关键字错误 . 它必须与 groupjoinselect 子句一起使用 . 像这样的东西:

var results = (from line in xferLinesTable.AsEnumerable()
              join invmast in inv_mast.AsEnumerable()
              on line.Field<int>("inv_mast_uid") equals invmast.Field<int>("inv_mast_uid")

              let extended_weight = line.Field<decimal>("quantity_requested") * line.Field<decimal>("unit_size") * invmast.Field<decimal>("net_weight")

              let extended_volume = line.Field<decimal>("quantity_requested") * line.Field<decimal>("unit_size") * invmast.Field<decimal>("cube")

              group new {weight = extended_weight,volume = extended_volume} by "A" into lines

              select new {weightTotal = lines.Sum(x => x.weight), volumeTotal = lines.Sum(x => x.volume)}).FirstOrDefault();

3 years ago

Aggregate可能是你需要的 .