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

C# 如何从LINQ查询将匿名类型转换为强类型,c#,entity-framework,linq,C#,Entity Framework,Linq,我编写了一个LINQ查询,它返回一个新类型的类,因为我使用了GROUPBY。因此,我创建了一个新类来将匿名类型强制转换为强类型。这是我的LINQ var result = rpt .GroupBy(x => new { CreateTime = EntityFunctions.TruncateTime(x.CreatedTime), x.UserId,

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

如何将此匿名对象转换为强对象?

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

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();
列表结果=
...
.选择(x=>new UserTransactionReport
{
UserId=x.Key.UserId,
ProjectId=x.Key.ProjectId,
CreateTime=x.Key.CreateTime,
TotalMinutesPent=x.Sum(z=>z.MinutesPent)
}).ToList();

为什么不立即创建一个
UserTransactionReport
呢?嘿,万一我只有一个对象?MyObj=新的{properties…};我有一个具有相同属性的DayInfo类,如何才能转换单个对象?@AlexanderDerck,为什么在Select子句中的“new UserTransactionReport”后面不需要括号?@Grace,它被称为对象初始值设定项:@AlexanderDerck Thx以获取帮助^_^
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();