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

5

我写了一个LINQ查询,它返回一个新类型的类,因为我使用了GROUP BY。因此,我创建了一个新类将匿名类型转换为强类型。以下是我的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();

我新创建的类如下所示...

public class UserTransactionReport
{
    public int UserId { get; set; }
    public int ProjectId { get; set; }
    public DateTime CreateTime { get; set; }
    public int TotalMinutesSpent { get; set; }
}

如何将此匿名转换为强类型?

为什么不立即创建一个 UserTransactionReport 呢? - vgru
1个回答

19

您可以在选择器中创建强类型对象:

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();

嘿,如果我有一个单一的对象?MyObj = new { properties ...}; 而且我有一个具有相同属性的DayInfo类,我该如何转换这个单一的对象? - Uladz Kha
@AlexanderDerck,为什么在Select子句中“new UserTransactionReport”后面不需要括号? - Grace
1
@Grace 这被称为对象初始化器:https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers - Alexander Derck
@AlexanderDerck 感谢您的帮助。^_^ - Grace

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接