Skip to content

Instantly share code, notes, and snippets.

@trapezoid
Created September 9, 2014 06:39
Show Gist options
  • Save trapezoid/5b0f0ea8ad7f3aa4f442 to your computer and use it in GitHub Desktop.
Save trapezoid/5b0f0ea8ad7f3aa4f442 to your computer and use it in GitHub Desktop.
deathly LINQ sample
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