private static Set TopCountWithTiesInternal(Set InputSet, int NCount, Expression SortExpression, bool Desc) { List <TupleValue> TupleValues = new List <TupleValue>(); PriorityQueue queue = new PriorityQueue(); foreach (Tuple t in InputSet.Tuples) { double dblValue = (double)SortExpression.Calculate(t); if (!Desc) { dblValue = -dblValue; } TupleValue tv = new TupleValue(t, dblValue); bool bInsertTuple = false; if (queue.Count < NCount || queue.CountWithoutTies < NCount) //short circuit on simple count... only hit CountWithTies when needed { bInsertTuple = true; } else { TupleValue r = (TupleValue)queue.Peek(); int cmp = tv.CompareTo(r); if (cmp > 0) { //a new lower value is being added which bumps off the highest value //if there's a tie for the highest value, bump all the ties off while (r.CompareTo((TupleValue)queue.Peek()) == 0) { queue.Pop(); } bInsertTuple = true; } else if (cmp == 0) { bInsertTuple = true; } } if (bInsertTuple) { queue.Push(tv); } } System.Collections.Generic.Stack <TupleValue> stack = new System.Collections.Generic.Stack <TupleValue>(queue.Count); while (queue.Count > 0) { TupleValue tv = (TupleValue)queue.Pop(); stack.Push(tv); } SetBuilder sb = new SetBuilder(); while (stack.Count > 0) { TupleValue tv = stack.Pop(); sb.Add(tv.Tuple); } return(sb.ToSet()); }