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.
what I have tried,
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();
and I would like to loop through the result cpus
to perform further other steps.
but I get the following error
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<FNC_RAQIT_HM_UI.UsageCPU>'.
EDIT
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..)
}
kindly help !!
Use
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();
Update as per error
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();
try to select a not new
when you select new you get anonymous type which can't be casted to UsageCPU
type
(from a in db.UsageCPUs
where a.ServerID.Contains(match)
group a by a.ServerID into b
orderby b.Key
select a)
or use var and then loop through the results
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() }).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With