Reputation: 2901
I don't often use LINQ and the thing about it is that there are efficient ways of using it an less efficient ways.
I have a list of items, and I simply want to do a calculation on each and return the lowest calculated decimal number (note number, not item). I have this LINQ which works but I wonder if it is the most efficient way LINQ can be used in this scenario.
var bestPrice = query.Select(x => new
{
Interest = CalcInterest(amount, term, x.ProductRate.Rate)
})
.OrderBy(x => x.Interest)
.FirstOrDefault();
Where "query" is a preselected LINQ list, and "CalcInterest" is a method used to calculate the number.
This query will be used a lot, so any small gains will be big wins.
Upvotes: 0
Views: 91
Reputation: 887
You don't need anonymous types here, I think. Try this:
var bestPrice = query.Min(x => CalcInterest(amount, term, x.ProductRate.Rate));
Edit: playing around with it I realized this created a different result. Your code returns an anon type. This just returns the object which has the lowest interest. The interest data isn't preserved.
Either way, use Min
to get the minimum.
Upvotes: 7