private static LinkedList <Ranges> Compact(int size, ISet <Ranges> inputRanges) { LinkedList <Ranges> ranges = new LinkedList <Ranges>(inputRanges); for (int i = size - 1; i >= 0; --i) { List <Ranges> toRemove = new List <Ranges>(); Ranges last = null; foreach (Ranges item in ranges) { if (last == null) { last = item; } else if (last.Merge(i, item)) { //it.remove(); toRemove.Add(item); } else { last = item; // go to next } } // Purge removable items foreach (var item in toRemove) { ranges.Remove(item); } } ; return(ranges); }