patterncsharpMinor
LINQ Group query - simplifying
Viewed 0 times
querylinqgroupsimplifying
Problem
Is there a way of writing this correctly working query more efficiently? I'm asking only to learn LINQ better:
var cpuInfo = edgeLPs
.GroupBy(k => k.CPU.ID, e => e.CPU)
.ToDictionary(k => k.Key, v => new
{
LogicalProcs = v.First().LogicalProcessorsCount,
Cores = v.First().Cores.Count,
SMT = v.First().SMT
});Solution
First, the usual disclaimer about performance: most of the time, you shouldn't worry much about it. If you find that your code is too slow, you should measure to find out which part is causing the slowdown and improve that. Trying to make code that's not performance critical more efficient is often a waste of your time.
In your specific case, I don't think the calls to
Though the change from
Also, I think that using
In your specific case, I don't think the calls to
First() would hurt your performance. But I would understand if you wanted to fix that to make your code more DRY. To do that, you could use Select():var cpuInfo = edgeLPs
.GroupBy(e => e.CPU.ID, e => e.CPU)
.Select(g => new { id = g.Key, cpu = g.First() })
.ToDictionary(g => g.id, g => new
{
LogicalProcs = g.cpu.LogicalProcessorsCount,
Cores = g.cpu.Cores.Count,
SMT = g.cpu.SMT
});Though the change from
.First() to something like .cpu isn't actually much of an improvement.Also, I think that using
First() like this can be a sign of faulty logic. If you know that there will be always at most one CPU with a given ID, then you should use Single() instead, or, in your case, simply use ToDictionary() without the preceding GroupBy(). If there can be multiple CPUs with the same ID, i think you should figure out what to do with the rest of them, and not simply ignore all but the first one.Code Snippets
var cpuInfo = edgeLPs
.GroupBy(e => e.CPU.ID, e => e.CPU)
.Select(g => new { id = g.Key, cpu = g.First() })
.ToDictionary(g => g.id, g => new
{
LogicalProcs = g.cpu.LogicalProcessorsCount,
Cores = g.cpu.Cores.Count,
SMT = g.cpu.SMT
});Context
StackExchange Code Review Q#25615, answer score: 3
Revisions (0)
No revisions yet.