我编写了一个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();
我新创建的课程如下...
public class UserTransactionReport
{
public int UserId { get; set; }
public int ProjectId { get; set; }
public DateTime CreateTime { get; set; }
public int TotalMinutesSpent { get; set; }
}
如何将此匿名转换为强?
答案 0 :(得分:13)
您可以在选择中创建强类型对象:
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();