I am discovering the tools C# provides to work with collections.
Suppose I have a List of elements, and I want to retrieve the one that most satisfies a property. Basically a elements.Max(predicate), except that I am interested in the index of the best element. The reason I want the index and not the element itself is there might not be such element, and the type is non-nullable.
Writing a function doing this is trivial, but I am interested in using the expressiveness of the tools C# provides to get a solution that is both concise, clear, and optimal (O(n)).
At this point I have the following code, which still looks cluttered, and evaluates the property twice.
List<foo> elements;
private int getBest(object x)
{
var indices = Enumerable.Range(0, elements.Count);
return indices.Aggregate(-1, (best, next) =>
(-1 == best || eval(x, elements[next]) > eval(x, elements[best])) ? next : best);
}
How can I make this piece of code better?
Addendum: I didn’t put it in the code for the sake of clarity, but if eval() is below a certain threshold the element is discarded.
I’d recommend using the
Selectin conjunction withAggregateLINQ extension methods. Using theSelectmethod you can create an anonymous type which houses theindexandvalueof each item within your collection. Then using the LINQAggregatemethod, you can narrow down the item with the greatest value. Some like this should work I think: