LINQ Group By多列,也算

时间:2018-11-22 15:32:33

标签: c# mysql linq pomelo

.NET Core应用程序中有以下LINQ代码。我正在将EF Core和Pomelo用作MySQL的驱动程序。

var journeyId = 5917;
var journey = Journeys.FirstOrDefault(j => j.JourneyId == journeyId);

var journeyEvents = from ad in AccelerometerData
                    join ae in AccelerometerEvents on ad.AccelerometerDataId equals ae
                        .AccelerometerData.AccelerometerDataId
                    where ad.Device.DeviceId == journey.Device.DeviceId && ae.TimeStamp >= journey.StartDateTime &&
                          ae.TimeStamp <= journey.EndDateTime
                    group ae by new
                    {
                        ae.EventType,
                        ae.Level
                    } into g
                    select new
                    {
                        EventType = new JourneyEventType { JourneyEventTypeId = g.Key.EventType },
                        Level = g.Key.Level,
                        Count = g.ToList().Count()
                    };

journey.JourneyEvents = journeyEvents.ToList();

当代码尝试运行最后一行时,出现以下异常。

  

无法解析表达式'g.ToList()':当前不支持方法'System.Linq.Enumerable.ToList'的重载。

我想念什么?

2 个答案:

答案 0 :(得分:2)

使用 g.Count()代替g.ToList()。Count()。

var journeyEvents = from ad in AccelerometerData
                    join ae in AccelerometerEvents on ad.AccelerometerDataId equals ae
                        .AccelerometerData.AccelerometerDataId
                    where ad.Device.DeviceId == journey.Device.DeviceId && ae.TimeStamp >= journey.StartDateTime &&
                          ae.TimeStamp <= journey.EndDateTime
                    group ae by new
                    {
                        ae.EventType,
                        ae.Level
                    } into g
                    select new
                    {
                        EventType = new JourneyEventType { JourneyEventTypeId = g.Key.EventType },
                        Level = g.Key.Level,
                        Count = g.Count()
                    };

journey.JourneyEvents = journeyEvents.ToList();

答案 1 :(得分:0)

我认为您应该在此处使用SelectToMany:

g.SelectToMany(gr => gr).ToList().Count()