如何转换通用列表<匿名类型>到通用列表< Classname> ;? [英] How to convert Generic List<anonymous type > to Generic List <Classname>?
问题描述
我有一个数据库,每'n'秒插入一次CPU使用率,我的任务是从数据库中获取最新的CPU条目.我想显示数据库tat中属于特定服务器的最新CPU条目,并将结果保存到通用列表中.
I have a database, where the CPU usage is inserted for every 'n' seconds and my task is to get the latest CPU entry from the database. I would like to display the latest CPU entry from the database tat belongs to the particular server , and I would like to save the result into a generic list.
我尝试过的,
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
以执行其他步骤.
and I would like to loop through the result cpus
to perform further other steps.
但出现以下错误
无法隐式转换类型 'System.Collections.Generic.List< AnonymousType#1>' "System.Collections.Generic.List< FNC_RAQIT_HM_UI.UsageCPU>".
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<FNC_RAQIT_HM_UI.UsageCPU>'.
编辑
更新
来自Satpal的以下查询对我有用..但是使用var
UPDATE
The following query from Satpal worked for me.. but using 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();
根据错误更新
无法在LINQ to Entities查询中构造实体
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();
这篇关于如何转换通用列表<匿名类型>到通用列表< Classname> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!