Exemple #1
0
        public static IEnumerable <M> GetNLargest <M>(this IComparer <M> g, IEnumerable <M> source, int n)
        {
            if (n < 0)
            {
                return(g.GetNSmallest(source, -n));
            }
            if (n == 0)
            {
                return(Enumerable.Empty <M>());
            }
            var sourceList = source.ToList();

            n = Math.Min(sourceList.Count, n);
            var resSet     = sourceList.Take(n).ToList();
            var currentMin = g.Min(resSet);

            foreach (var t in sourceList.Skip(n))
            {
                if (g.Compare(t, currentMin) <= 0)
                {
                    continue;
                }
                resSet.Remove(currentMin);
                resSet.Add(t);
                currentMin = g.Min(resSet);
            }
            return(resSet.OrderByDescending(i => i, g));
        }