, MoveNext() false , , , :
public static TResult MaxOrDefault<T, TResult>(this IEnumerable<T> source, Func<T, TResult> func) where TResult : IComparable
{
if(source == null)
throw new ArgumentNullException("source");
using(var en = source.GetEnumerator())
if(en.MoveNext())
{
TResult max = func(en.Current);
while(en.MoveNext())
{
TResult cur = func(en.Current);
if(max == null || (cur != null && cur.CompareTo(max) > 0))
max = cur;
}
return max;
}
else
return default(TResult);
}
, , IEnumerable ( IQueryable, ). , Linq, IQueryable , IQueryable:
public static TResult MaxOrDefault<T, TResult>(this IQueryable<T> source, Func<T, TResult> func) where TResult : IComparable
{
if(source == null)
throw new ArgumentNullException("source");
return source.OrderByDescending(func).Select(func).FirstOrDefault();
}
Linq, , SQL.
But it is less efficient than our earlier version for enumerations in memory, but provided that both options usually allow normal overloads to be better chosen.
source
share