简体   繁体   English

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

[英]How to convert Anonymous Type to Strong Type from LINQ query

I have written a LINQ query which returns a new type of class, becuse I have used GROUP BY. 我写了一个LINQ查询,它返回一个新类型,因为我使用了GROUP BY。 Therefore, I have created a new class to cast Anonymous type to Strong Type. 因此,我创建了一个新类来将Anonymous类型转换为Strong Type。 Here is my LINQ... 这是我的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();

My newly created class is like below... 我新创建的课程如下...

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

How can I convert this anonymous to strong? 如何将此匿名转换为强大?

You can create strongly typed objects in the select: 您可以在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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM