daily pastebin goal
36%
SHARE
TWEET

Untitled

a guest Aug 21st, 2018 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. expression tree instead of using LINQ
  2. public static IEnumerable<T> TakeTopDistinct<T>(this IEnumerable<T> source, int count)
  3. {
  4.     if (source == null) throw new ArgumentNullException("source");
  5.     if (count < 0) throw new ArgumentOutOfRangeException("count");
  6.     if (count == 0) yield break;
  7.  
  8.     var comparer = Comparer<T>.Default;
  9.     LinkedList<T> selected = new LinkedList<T>();
  10.  
  11.     foreach(var value in source)
  12.     {
  13.         if(selected.Count < count // need to fill
  14.             || comparer.Compare(selected.Last.Value, value) < 0 // better candidate
  15.             )
  16.         {
  17.             var tmp = selected.First;
  18.             bool add = true;
  19.             while (tmp != null)
  20.             {
  21.                 var delta = comparer.Compare(tmp.Value, value);
  22.                 if (delta == 0)
  23.                 {
  24.                     add = false; // not distinct
  25.                     break;
  26.                 }
  27.                 else if (delta < 0)
  28.                 {
  29.                     selected.AddBefore(tmp, value);
  30.                     add = false;
  31.                     if(selected.Count > count) selected.RemoveLast();
  32.                     break;
  33.                 }
  34.                 tmp = tmp.Next;
  35.             }
  36.             if (add && selected.Count < count) selected.AddLast(value);
  37.         }
  38.     }
  39.     foreach (var value in selected) yield return value;
  40. }
  41.    
  42. List<T> GetFirstNElements (IList<T> list, int n) where T :IComparable <T>{
  43.     list.Sort();
  44.     List<T> returnList = new List<T>();
  45.     for(int i = 0; i<n; i++){
  46.         returnList.Add(list[i]);
  47.     }
  48.     return returnList;
  49. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top