Created
September 9, 2014 06:39
-
-
Save trapezoid/5b0f0ea8ad7f3aa4f442 to your computer and use it in GitHub Desktop.
deathly LINQ sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace LinqTest | |
{ | |
public static class HavingMaxByExtension | |
{ | |
private static TSource HavingMaxByInternal<TSource, TValue>(IEnumerable<TSource> source, Func<TSource, TValue> maxFunc) | |
where TSource : class | |
where TValue : struct, IComparable<TValue> | |
{ | |
TSource maxItem = null; | |
TValue? maxValue = null; | |
foreach (var item in source) | |
{ | |
TValue itemValue = maxFunc.Invoke(item); | |
if (maxValue.HasValue == false || itemValue.CompareTo(maxValue.Value) >= 0) { | |
maxItem = item; | |
maxValue = itemValue; | |
} | |
} | |
return maxItem; | |
} | |
public static TSource HavingMaxBy<TSource>(this IEnumerable<TSource> source, Func<TSource, int> maxFunc) where TSource : class | |
{ | |
return HavingMaxByInternal(source, maxFunc); | |
} | |
public static TSource HavingMaxBy<TSource>(this IEnumerable<TSource> source, Func<TSource, float> maxFunc) where TSource : class | |
{ | |
return HavingMaxByInternal(source, maxFunc); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment