Advertisement
Guest User

Untitled

a guest
Sep 24th, 2016
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. public static void Main(string[] args)
  2. {
  3.     var users = new List<User> {
  4.         new User("Ballmer", 60),
  5.         new User("Satya", 49),
  6.         new User("Bill", 60),
  7.     };
  8.     users
  9.         .MaxBy(s => s.Name)
  10.         .Then(s => Console.WriteLine($"Max user = {s}"));
  11. }
  12.  
  13. public static class LinqExtensions
  14. {
  15.     public static Optional<T> MaxBy<T, R>(this IEnumerable<T> source, Func<T, R> selector) where R : IComparable<R>
  16.     {
  17.         bool isFirst = true;
  18.         T max = default(T);
  19.         foreach (var s in source)
  20.         {
  21.             if (isFirst)
  22.             {
  23.                 max = s;
  24.                 isFirst = false;
  25.             }
  26.             else if (selector(s).CompareTo(selector(max)) > 0)
  27.             {
  28.                 max = s;
  29.             }
  30.         }
  31.         return isFirst ? new Optional<T>() : new Optional<T>(max);
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement