如何从LINQ查询中将匿名类型转换为强类型

Ari*_*MAZ 3 c# linq entity-framework

我写了一个LINQ查询,它返回一个新类型,因为我使用了GROUP BY.因此,我创建了一个新类来将Anonymous类型转换为Strong Type.这是我的LINQ ......

var result = rpt
    .GroupBy(x => new
                  {
                      CreateTime = EntityFunctions.TruncateTime(x.CreatedTime),
                      x.UserId,
                      x.ProjectId
                  })
    .Select(x => new
                 {
                     UserId = x.Key.UserId,
                     ProjectId = x.Key.ProjectId,
                     CreateTime = x.Key.CreateTime,
                     TotalMinutesSpent = x.Sum(z => z.MinutesSpent)
                 })
    .OfType<List<UserTransactionReport>>().ToList();
Run Code Online (Sandbox Code Playgroud)

我新创建的课程如下...

public class UserTransactionReport
{
    public int UserId { get; set; }
    public int ProjectId { get; set; }
    public DateTime CreateTime { get; set; }
    public int TotalMinutesSpent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何将此匿名转换为强大?

Ale*_*rck 13

您可以在select中创建强类型对象:

List<UserTransactionReport> result = 
    ...
    .Select(x => new UserTransactionReport
    {
       UserId = x.Key.UserId,
       ProjectId = x.Key.ProjectId,
       CreateTime = x.Key.CreateTime,
       TotalMinutesSpent = x.Sum(z => z.MinutesSpent)
    }).ToList();
Run Code Online (Sandbox Code Playgroud)