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 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.
edgeLPs
? \$\endgroup\$