Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Therefore, I have created a new class to cast Anonymous type to Strong Type. Here is my 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?

like image 528
Arif YILMAZ Avatar asked Dec 03 '22 15:12

Arif YILMAZ


1 Answers

You can create strongly typed objects in the 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();
like image 188
Alexander Derck Avatar answered Feb 24 '23 11:02

Alexander Derck