Is there a inline way to project properties after the new MinBy or MaxBy calls in C# 10 .Net 6?
double topPriceInList = prices.MaxBy(h => h.High)."Select(h => h.High)";
Certainly Visual Studio 2021 doesn't like any that I have tried.
CodePudding user response:
MaxBy(this IEnumerable<T>) and MinBy(this IEnumerable<T>) don't return IEnumerable<T> - they return single elements (i.e. T), so just do this:
double topPriceInList = prices.MaxBy(h => h.High).High;
That said, that code above doesn't need MaxBy, just use Max:
double topPriceInList = prices.Max(h => h.High);
// or:
double topPriceInList = prices.Select(h => h.High).Max();
- Note that
Min,Max,MinBy, andMaxBywill all throw an exception at runtime if the source collection is empty (or any previous.Wheresteps eliminated all elements) - ...so you may need to use
MinOrDefault,MaxOrDefault,MaxByOrDefault, orMaxByOrDefault, in which case use the null-safe navigation operator?.(aka elvis-operator).- But make sure the
...OrDefault()extension-method is invoked onIEnumerable<Nullable<T>>and notIEnumerable<T>becausedefault(T)for value-types is nevernullwhich is a frequent source of bugs.
- But make sure the
double? topPriceInListOrNull = prices.Select(h => (double?)h.High).MaxOrDefault();
