gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:21:53 25 4
gpt4 key购买 nike

我编写了一个返回新类类型的 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; }
}

如何将这个匿名转换为强?

最佳答案

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

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

关于c# - 如何从 LINQ 查询将匿名类型转换为强类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35623391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com