通过SUM LINQ C#SELECT GROUP

时间:2015-10-09 01:14:40

标签: c# linq

我有一些表格,我正在加入LINQ,这是第一次使用它,所以我不熟悉它。

下一个查询如下:

var query = from catalogoV in catalogo_DT.AsEnumerable() 
            where catalogoV.Field<String>("Incluye GPS") == "yes"
                join vehicle in vehicleData.AsEnumerable()
                     on catalogoV.Field<String>("Numero Economico") equals vehicle.Field<String>("DisplayName")
                join actividad in activityData.AsEnumerable() 
                     on vehicle.Field<Guid>("VehicleId") equals actividad.Field<Guid>("VehicleId")   
                select new {Displayname = catalogoV.Field<String>("Numero Economico"), ID = vehicle.Field<Guid>("VehicleId"), Increment = actividad.Field<Single>("IncrementalDistance") };

这是我得到的结果的一个例子

{ Displayname = "0DNP-625", ID = {651e5858-bc54-4459-a5de-31144eed3374}, Increment = 0.1 }
{ Displayname = "0DNP-625", ID = {651e5858-bc54-4459-a5de-31144eed3374}, Increment = 0.4 }
{ Displayname = "0DNP-625", ID = {651e5858-bc54-4459-a5de-31144eed3374}, Increment = 4.5 }
{ Displayname = "0003-333", ID = {ecb42206-397f-4cff-bf53-4aac8877491c}, Increment = 0.5 }
{ Displayname = "0003-333", ID = {ecb42206-397f-4cff-bf53-4aac8877491c}, Increment = 5.2 }

但我真的想要得到增量的总和,而不是它的所有行。 如:

{ Displayname = "0003-333", ID = {ecb42206-397f-4cff-bf53-4aac8877491c}, Increment = 5.7 }
{ Displayname = "0DNP-625", ID = {ecb42206-397f-4cff-bf53-4aac8877491c}, Increment = 5.0 }

根据我的阅读,我需要在我的陈述中放置一个gorup,但我不知道我应该如何将它与我的选择混合,我在参考MSDN上找不到这样的东西

1 个答案:

答案 0 :(得分:1)

您可能需要为actividad字段使用组连接,而不仅仅是加入。方法如下:

var query =
    from catalogoV in catalogo_DT.AsEnumerable()
    where catalogoV.Field<String>("Incluye GPS") == "yes"
    join vehicle in vehicleData.AsEnumerable()
        on catalogoV.Field<String>("Numero Economico") equals vehicle.Field<String>("DisplayName")
    join actividad in activityData.AsEnumerable()
        on vehicle.Field<Guid>("VehicleId") equals actividad.Field<Guid>("VehicleId")
        into actividads
    let ID = vehicle.Field<Guid>("VehicleId")
    orderby ID
    select new
    {
        Displayname = catalogoV.Field<String>("Numero Economico"),
        ID,
        Increment = actividads.Sum(x => x.Field<Single>("IncrementalDistance"))
    };

我根据您的评论添加了订单。