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

标签 c# linq

我有一个数据库,其中每“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/

相关文章:

c# - LINQ 左 JOIN 错误

c# - .net core中使用表达式进行动态分组

asp.net - Entity Framework (模型优先)删除具有相同属性的多个条目

c# - 在 .NET 中使用整数填充列表的更简单方法

c# - 连接未打开

c# - GoogleWebAuthorizationBroker 无法使用 https//accounts.google.com/o/oauth2/v2/auth 启动浏览器;重定向 uri 不匹配

c# - System.Diagnostics.Debugger.Debug() 停止工作

c# - 是否有 string.Join(string, string[]) 的 LINQ 等价物

c# - 与 ASPNET Core 和 websockets 的双向通信

c# - 如何在 DropDownList 控件中列出 Active Directory 中的所有用户