Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void Main(string[] args)
- {
- var users = new List<User> {
- new User("Ballmer", 60),
- new User("Satya", 49),
- new User("Bill", 60),
- };
- users
- .MaxBy(s => s.Name)
- .Then(s => Console.WriteLine($"Max user = {s}"));
- }
- public static class LinqExtensions
- {
- public static Optional<T> MaxBy<T, R>(this IEnumerable<T> source, Func<T, R> selector) where R : IComparable<R>
- {
- bool isFirst = true;
- T max = default(T);
- foreach (var s in source)
- {
- if (isFirst)
- {
- max = s;
- isFirst = false;
- }
- else if (selector(s).CompareTo(selector(max)) > 0)
- {
- max = s;
- }
- }
- return isFirst ? new Optional<T>() : new Optional<T>(max);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement