gpt4 book ai didi

c# - 如何将通用列表<匿名类型>转换为通用列表<类名>?

转载 作者:太空狗 更新时间:2023-10-29 22:14:03 25 4
gpt4 key购买 nike

我有一个数据库,其中每“n”秒插入一次 CPU 使用率,我的任务是从数据库中获取最新的 CPU 条目。我想显示属于特定服务器的数据库中的最新 CPU 条目,我想将结果保存到通用列表中。

我试过的,

    string match = "ServerX"

List<UsageCPU> cpus = (from a in db.UsageCPUs
where a.ServerID.Contains(match)
group a by a.ServerID into b
orderby b.Key
select new { ServerID = b.Key,
Usage = b.FirstOrDefault() }).ToList();

我想遍历结果 cpus 以执行进一步的其他步骤。

但我得到以下错误

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<FNC_RAQIT_HM_UI.UsageCPU>'.

编辑

enter image description here更新来自 Satpal 的以下查询对我有用..但使用 var

   var cpus = (from a in db.UsageCPUs
where a.ServerID.Contains(match)
group a by a.ServerID into b
orderby b.Key
select new
{
ServerID = b.Key,
Usage = b.FirstOrDefault().Usage
}).ToList();

foreach (var item in cpus)
{
if(bla bla..)
}

请帮忙!!

最佳答案

使用

List<UsageCPU> cpus = (from a in db.UsageCPUs
where a.ServerID.Contains(match)
group a by a.ServerID into b
orderby b.Key
select new UsageCPU //Added UsageCPU
{
ServerID = b.Key,
Usage = b.FirstOrDefault().Usage
}).ToList();

根据错误更新

The entity cannot be constructed in a LINQ to Entities query

List<UsageCPU> cpus = (from a in db.UsageCPUs
where a.ServerID.Contains(match)
group a by a.ServerID into b
orderby b.Key
select new
{
ServerID = b.Key,
Usage = b.FirstOrDefault().Usage
})
.AsEnumerable()
.Select(x => new UsageCPU
{
ServerID ,
Usage
}).ToList();

关于c# - 如何将通用列表<匿名类型>转换为通用列表<类名>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17275871/

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