Linq performance poor

In a for loop I run the following code:

IEnumerable<KeyValuePair<DateTime, double>> avrPrefMinute = d_averagesPerMinute.Where(n => n.Key == minuteAverage.Key.Subtract(new TimeSpan(0, i, 0)));

This loop will always run 20 times, but when I inspect the application with VS2012 Analyser it tells me, it performs poor.

enter image description here

Can someone tell me how to refactor this with a more fast solution. I've read about predicates, but I'm not able to get them right.

Jon Skeet
people
quotationmark

Well, it looks to me like minuteAverage.Key.Subtract(new TimeSpan(0, i, 0)) doesn't depend on anything within the loop. So extract that:

var target = minuteAverage.Key.Subtract(new TimeSpan(0, i, 0));
var avrPrefMinute = d_averagesPerMinute.Where(n => n.Key == target);

Of course, if d_averagesPerMinute is a Dictionary<DateTime, double> you can just do a lookup instead:

var target = minuteAverage.Key.Subtract(new TimeSpan(0, i, 0));
double result;
if (d_averagesPerMinute.TryGetValue(target, out result))
{
    // Use result
}
else
{
    // No result found
}

Also, I'd actually suggest that rather than

minuteAverage.Key.Subtract(new TimeSpan(0, i, 0))

you use

minuteAverage.Key.AddMinutes(-i);

That's clearer, in my view.

people

See more on this question at Stackoverflow