public void Sort(int[][] array, IComparer comparer) { if (comparer == null || array == null) throw new ArgumentNullException("Arguments can't be null."); QuickSort(array, 0, array.GetLength(0) - 1, comparer.Compare); }
/// <summary> /// A simple bubble sort for two arrays, limited to some region of the arrays. /// This is a regular bubble sort, nothing fancy. /// </summary> public static void SimpleSort(Array array, Array items, int startingIndex, int length, IComparer comparer) { bool finished = false; while (!finished) { bool swapped = false; for (int g = startingIndex; g < startingIndex + length - 1; g++) { Object first = array.GetValue(g); Object second = array.GetValue(g + 1); int comparison = comparer.Compare(first, second); if (comparison == 1) { Swap(g, g + 1, array, items); swapped = true; first = array.GetValue(g); second = array.GetValue(g + 1); } } if (!swapped) { finished = true; } } }
/// <summary> /// Creates a new instance of the <see cref="ListViewTextColumnComparer"/> class /// with the specified string comparer. /// </summary> /// <param name="stringComparer">The string comparer used to compare the item texts.</param> public ListViewTextColumnComparer(IComparer<string> stringComparer) { if (stringComparer == null) { throw new ArgumentNullException("stringComparer"); } this.stringComparer = stringComparer; }
public SortedList() { this.keys = emptyArray; this.values = emptyArray; this._size = 0; this.comparer = new Comparer(CultureInfo.CurrentCulture); }
public void Sort( int index, int count, IComparer comparer) { theList.Sort(index, count, comparer); }
public Index(File file, string name, BiosParameterBlock bpb, UpperCase upCase) { _file = file; _name = name; _bpb = bpb; _isFileIndex = name == "$I30"; _blockCache = new ObjectCache<long, IndexBlock>(); _root = _file.GetStream(AttributeType.IndexRoot, _name).GetContent<IndexRoot>(); _comparer = _root.GetCollator(upCase); using (Stream s = _file.OpenStream(AttributeType.IndexRoot, _name, FileAccess.Read)) { byte[] buffer = Utilities.ReadFully(s, (int)s.Length); _rootNode = new IndexNode(WriteRootNodeToDisk, 0, this, true, buffer, IndexRoot.HeaderOffset); // Give the attribute some room to breathe, so long as it doesn't squeeze others out // BROKEN, BROKEN, BROKEN - how to figure this out? Query at the point of adding entries to the root node? _rootNode.TotalSpaceAvailable += _file.MftRecordFreeSpace(AttributeType.IndexRoot, _name) - 100; } if (_file.StreamExists(AttributeType.IndexAllocation, _name)) { _indexStream = _file.OpenStream(AttributeType.IndexAllocation, _name, FileAccess.ReadWrite); } if (_file.StreamExists(AttributeType.Bitmap, _name)) { _indexBitmap = new Bitmap(_file.OpenStream(AttributeType.Bitmap, _name, FileAccess.ReadWrite), long.MaxValue); } }
/// <summary> /// Rearranges the array in ascending order, using the natural order. /// </summary> /// <param name="a">a the array to be sorted</param> public static void Sort(IComparable[] a, IComparer c = null) { //make sure we have the comparer passed by argument or create default IComparer comparer = c ?? Comparer<object>.Default; int N = a.Length; int h = 1; //3*x +1 -> 1, 4, 13, 40, 121, 364, .. while (h < N / 3) { h = 3 * h + 1; } while (h >= 1) { //h- sort array for (int i = h; i < N; i++) { for (int j = i; j >= h && less(comparer, a[j], a[j - h]); j -= h) { exch(a, j, j - h); } } Debug.Assert(isHsorted(a, comparer, h)); h = h / 3; } Debug.Assert(isSorted(a, comparer)); }
/// <summary> /// 初始化服务容器 /// </summary> /// <param name="serviceName"> 服务约定名称 </param> /// <param name="serviceType"> 服务约定基类或接口类型 </param> /// <param name="typeComparer"> 比较2个类型服务的优先级 </param> /// <param name="logger"> 日志记录器 </param> /// <exception cref="ArgumentNullException"> /// <paramref name="serviceName" /> and <paramref name="serviceType" /> is all /// <see langword="null" />. /// </exception> /// <exception cref="OverflowException"> 匹配插件数量超过字典的最大容量 (<see cref="F:System.Int32.MaxValue" />)。 </exception> protected ServiceContainer(string serviceName, Type serviceType, IComparer<Type> typeComparer, TraceSource logger = null) { TypeComparer = typeComparer; _logger = logger ?? LogServices.Logger; _items = new ConcurrentDictionary<Type, ServiceItem>(); _logger?.Write(TraceEventType.Start, $"开始扫描服务插件 serviceName={serviceName},serviceType={serviceType}"); foreach (var p in MEF.PlugIns.GetPlugIns(serviceName, serviceType).OrderByDescending(p => p.Priority)) { var value = p.GetValue(serviceType); if (value == null) { continue; } var type = GetServiceType(p, value); if (type == null) { continue; } var item = new ServiceItem(this, type, value, p); item.MakeSystem(); //默认为系统插件 if (_items.TryAdd(type, item) == false) { _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName})因优先级({p.Priority})过低被抛弃"); } else { _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName}),优先级({p.Priority})装载完成"); } } _logger?.Write(TraceEventType.Stop, $"服务插件装载完成,有效服务 {Count} 个"); }
public override void AddSort(object expr, IComparer comparer) { // sort makes sense only when we are dealing with a query that // returns a nodeset. Query evalExpr; string query = expr as string; if (query != null) { evalExpr = new QueryBuilder().Build(query, out _needContext); // this will throw if expr is invalid } else { CompiledXpathExpr xpathExpr = expr as CompiledXpathExpr; if (xpathExpr != null) { evalExpr = xpathExpr.QueryTree; } else { throw XPathException.Create(SR.Xp_BadQueryObject); } } SortQuery sortQuery = _query as SortQuery; if (sortQuery == null) { _query = sortQuery = new SortQuery(_query); } sortQuery.AddSort(evalExpr, comparer); }
// Helper method for sorting an ArrayList. If the comparer is a SortFieldComparer, // use the cached-value approach to avoid excessive reflection. For other // comparers, sort the usual way internal static void SortHelper(ArrayList al, IComparer comparer) { SortFieldComparer sfc = comparer as SortFieldComparer; if (sfc == null) { // sort the usual way al.Sort(comparer); } else { // Sort with cached values. // Step 1. Copy the items into a list augmented with slots for // the cached values. int n = al.Count; int nFields = sfc._fields.Length; CachedValueItem[] list = new CachedValueItem[n]; for (int i=0; i<n; ++i) { list[i].Initialize(al[i], nFields); } // Step 2. Sort the augmented list. The SortFieldComparer will // fill in the slots as necessary to perform its comparisons. Array.Sort(list, sfc); // Step 3. Copy the items back into the original list, now in // sorted order for (int i=0; i<n; ++i) { al[i] = list[i].OriginalItem; } } }
public ListDictionary () { count = 0; version = 0; comparer = null; head = null; }
public ListViewColumnSorter() { SortColumn = 0; SortOrder = SortOrder.Ascending; mComparer = new CaseInsensitiveComparer(); }
public ListViewColumnSorter(IComparer comparer) { SortColumn = 0; SortOrder = SortOrder.Ascending; mComparer = comparer; }
/// <summary> /// Initializes a new instance of the SorterBase class with the specified /// TableModel, Column index, IComparer and SortOrder /// </summary> /// <param name="tableModel">The TableModel that contains the data to be sorted</param> /// <param name="column">The index of the Column to be sorted</param> /// <param name="comparer">The IComparer used to sort the Column's Cells</param> /// <param name="sortOrder">Specifies how the Column is to be sorted</param> public SorterBase(TableModel tableModel, int column, IComparer comparer, SortOrder sortOrder) { this.tableModel = tableModel; this.column = column; this.comparer = comparer; this.sortOrder = sortOrder; }
public AdaptiveGridArchive(int maxSize, int bisections, int objectives) : base(maxSize) { _maxSize = maxSize; _dominance = new DominanceComparator(); Grid = new AdaptiveGrid(bisections, objectives); }
/// <summary> /// Suspends sorting until ResumeSorting is called. Does so by clearing the ListViewItemSorter property. /// </summary> public void SuspendSorting() { if( suspendSortDepth == 0 ) { suspendedComparer = this.ListViewItemSorter; this.ListViewItemSorter = null; } suspendSortDepth++; }
public StockMessageFactory(IStockRepository repoA, IStockRepository repoB, IComparer<Stock> comparer, char userInput) { _repoA = repoA; _repoB = repoB; _comparer = comparer; _userInput = userInput; }
void GroundCheck() { Ray ray = new Ray(transform.position + Vector3.up * .1f, -Vector3.up); RaycastHit[] hits = Physics.RaycastAll(ray, .1f); rayHitComparer = new RayHitComparer(); System.Array.Sort(hits, rayHitComparer); if (velocity.y < jumpPower * .5f) { onGround = false; rigidBody.useGravity = true; foreach (var hit in hits) { if (!hit.collider.isTrigger) { if (velocity.y <= 0) { rigidBody.position = Vector3.MoveTowards(rigidBody.position, hit.point, Time.deltaTime * 100); } onGround = true; rigidBody.useGravity = false; } } } }
public SurvivedTextTreeCreator(IComparer<string> comparer) { if (comparer == null) throw new ArgumentNullException(); Comparer = comparer; }
/// <summary> /// The basic constructor does a quicksort using the built in comparer and swapper /// </summary> /// <param name="array">The array to sort.</param> public static void QuickSort(ArrayList array) { Sort s=new Sort(); Sort.comparer=s; Sort.swapper=s; QuickSort(array, 0, array.Count-1); }
private static bool AreCollectionsEqual(ICollection expected, ICollection actual, IComparer comparer, ref string reason) { Assert.CheckParameterNotNull(comparer, "Assert.AreCollectionsEqual", "comparer", string.Empty, new object[0]); if (!object.ReferenceEquals(expected, actual)) { if ((expected == null) || (actual == null)) { return false; } if (expected.Count != actual.Count) { reason = (string)TestingResources.NumberOfElementsDiff; return false; } IEnumerator enumerator = expected.GetEnumerator(); IEnumerator enumerator2 = actual.GetEnumerator(); for (int i = 0; enumerator.MoveNext() && enumerator2.MoveNext(); i++) { if (0 != comparer.Compare(enumerator.Current, enumerator2.Current)) { reason = (string)TestingResources.ElementsAtIndexDontMatch(i); return false; } } reason = (string)TestingResources.BothCollectionsSameElements; return true; } reason = (string)TestingResources.BothCollectionsSameReference(string.Empty); return true; }
private SetOp() { } // disable construction /// <summary> /// Computes union of two sorted sequences. /// </summary> /// <remarks> /// <para>Both set1 and set2 must be sorted in ascending order with respect to comparer.</para> /// <para>Union contains elements present in one or both ranges.</para> /// <para>Result is written to the output iterator one member at a time</para> /// /// <para>Union differs from <see cref="Merge">Merge</see> for multisets.</para> /// /// <para>If k equal elements are present in set1 and m elements equal to those k /// are present in set2,then k elements from set1 are included in the output, /// followed by max(m-k, 0) elements from set2. The total of max(k,m) are /// added to the output. If you'd like to have m+k elements, use Merge function. /// </para> /// <para>Complexity: linear on combined number of items in both sequences</para> /// </remarks> /// <example> /// <para>set1 = { "a", "test", "Test", "z" }</para> /// <para>set2 = { "b", "tEst", "teSt", "TEST", "Z" }</para> /// <para>comparer is a case-insensitive comparer</para> /// <para>The following elements will be added to output: /// {"a", "b", "test", "Test", "TEST", "z" }</para> /// </example> public static void Union(IEnumerable set1, IEnumerable set2, IComparer comparer, IOutputIterator output) { IEnumerator enum1 = set1.GetEnumerator(); IEnumerator enum2 = set2.GetEnumerator(); bool have1 = enum1.MoveNext(); bool have2 = enum2.MoveNext(); while (have1 && have2) { int compare = comparer.Compare(enum1.Current, enum2.Current); if (compare < 0) { output.Add(enum1.Current); have1 = enum1.MoveNext(); } else if (compare > 0) { output.Add(enum2.Current); have2 = enum2.MoveNext(); } else { output.Add(enum1.Current); have1 = enum1.MoveNext(); have2 = enum2.MoveNext(); } } while (have1) { output.Add(enum1.Current); have1 = enum1.MoveNext(); } while (have2) { output.Add(enum2.Current); have2 = enum2.MoveNext(); } }
// Methods public LastWriteTimeComparator(bool bAscending, IComparer subComparer) { this._IsAscending = true; this._InnerComparer = null; this.IsAscending = bAscending; this.InnerComparer = subComparer; }
public void TreeWithPointProvider(CustomPoint[] point, CustomPoint[] resultPoint, IComparer<CustomPoint> comparer) { var tree = new BinaryTree<CustomPoint>(point, comparer); var pointCompare = new PointComparer(); var enumeratorBook = tree.Preorder().ToArray(); CollectionAssert.AreEqual(enumeratorBook, resultPoint, pointCompare); }
public static PersistentTreeSet create(IComparer comp, ISeq init) { PersistentTreeSet ret = new PersistentTreeSet(null, new PersistentTreeMap(null, comp)); for (ISeq s = init; s != null; s = s.next()) ret = (PersistentTreeSet)ret.cons(s.first()); return ret; }
/// <summary> /// Check if the player is in collision with the ground /// </summary> void GroundCheck() { Ray ray = new Ray (transform.position + Vector3.up * .1f, -Vector3.up); RaycastHit[] hits = Physics.RaycastAll (ray, .1f); rayHitComparer = new RayHitComparer (); System.Array.Sort (hits, rayHitComparer); if (this.GetComponent<Rigidbody> ().velocity.y < jumpForce * .5f) { grounded = false; this.GetComponent<Rigidbody> ().useGravity = true; foreach (var hit in hits) { if (!hit.collider.isTrigger) { if (this.GetComponent<Rigidbody> ().velocity.y <= 0) { //this.GetComponent<Rigidbody> ().position = Vector3.MoveTowards (this.GetComponent<Rigidbody> ().position, hit.point, Time.deltaTime * 100); } candoubleJump = true; grounded = true; this.GetComponent<Rigidbody> ().useGravity = false; } } } else { grounded = false; this.GetComponent<Rigidbody> ().useGravity = true; } }
//========================================================================================== // Constructors //========================================================================================== /// <summary> /// Initializes a new instance of the <see cref="SortedCollection"/> class. /// </summary> /// <param name="comparer">An <see cref="IComparer"/> to use for the sorting.</param> protected SortedCollection(IComparer comparer) : base(new ArrayList()) { Tracer.VerifyNonNullArgument(comparer, "comparer"); this.comparer = comparer; this.list = (ArrayList)this.InnerCollection; }
/// <summary> /// Creates a new iterator, buffering entries from the specified iterator </summary> public BufferedInputIterator(IInputIterator source) { BytesRef spare; int freqIndex = 0; hasPayloads = source.HasPayloads; hasContexts = source.HasContexts; while ((spare = source.Next()) != null) { entries.Append(spare); if (hasPayloads) { payloads.Append(source.Payload); } if (hasContexts) { contextSets.Add(source.Contexts); } if (freqIndex >= freqs.Length) { freqs = ArrayUtil.Grow(freqs, freqs.Length + 1); } freqs[freqIndex++] = source.Weight; } comp = source.Comparator; }
public SortedList(IComparer comparer) : this() { if (comparer != null) { this.comparer = comparer; } }
/// <summary> /// /// </summary> /// <param name="identifier"></param> /// <param name="state"></param> /// <param name="metricsEvaluator"></param> /// <param name="endCriteriaEvaluator"></param> /// <param name="getCallableGenes">Gets the IGEPGenes that can be called by the given IGEPGene.</param> public GEPEnvironment(IEnvironmentIdentifier identifier, IEnvironmentState state, IMetricsEvaluator metricsEvaluator, IEndCriteriaEvaluator endCriteriaEvaluator, IComparer<IOrganism> organismValueComparer, ICallableGenesProvider callableGenesProvider) : base(identifier, state, metricsEvaluator, endCriteriaEvaluator, callableGenesProvider: callableGenesProvider, organismValueComparer: organismValueComparer) { }
static protected RangeView <TElement> FindUniqueRangeCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey min, TKey max, bool ascendant) { var lo = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, min, keySelector, comparer, false); var hi = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, max, keySelector, comparer, true); return(new RangeView <TElement>(indexArray, lo, hi, ascendant)); }
/// <summary> /// Create a new instance of priority queue with default initial capacity. /// </summary> /// <param name="comparer">Priority comparer. Default for type will be used unless custom is provided.</param> public ConcurrentPriorityQueue(IComparer<TPriority> comparer = null): this(_defaultCapacity, comparer) { }
/// <summary> /// Create a new instance of priority queue with given initial capacity. /// </summary> /// <param name="capacity">Initial queue capacity. Should be greater than 0.</param> /// <param name="comparer">Priority comparer. Default for type will be used unless custom is provided.</param> public ConcurrentPriorityQueue(int capacity, IComparer<TPriority> comparer = null):base(capacity, comparer) { _shrinkBound = Capacity / _shrinkRatio; }
/// <summary> /// Do not add an item to the cache unless the current transaction /// timestamp is later than the timestamp at which the item was /// invalidated. (Otherwise, a stale item might be re-added if the /// database is operating in repeatable read isolation mode.) /// </summary> /// <returns>Whether the item was actually put into the cache</returns> public async Task <bool> PutAsync(CacheKey key, object value, long txTimestamp, object version, IComparer versionComparator, bool minimalPut, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (txTimestamp == long.MinValue) { // MinValue means cache is disabled return(false); } using (await _lockObjectAsync.LockAsync()) { if (log.IsDebugEnabled()) { log.Debug("Caching: {0}", key); } var lockValue = await(_cache.LockAsync(key, cancellationToken)).ConfigureAwait(false); try { ILockable lockable = (ILockable)await(Cache.GetAsync(key, cancellationToken)).ConfigureAwait(false); bool puttable = lockable == null || lockable.IsPuttable(txTimestamp, version, versionComparator); if (puttable) { await(Cache.PutAsync(key, CachedItem.Create(value, Cache.NextTimestamp(), version), cancellationToken)).ConfigureAwait(false); if (log.IsDebugEnabled()) { log.Debug("Cached: {0}", key); } return(true); } else { if (log.IsDebugEnabled()) { if (lockable.IsLock) { log.Debug("Item was locked: {0}", key); } else { log.Debug("Item was already cached: {0}", key); } } return(false); } } finally { await(_cache.UnlockAsync(key, lockValue, cancellationToken)).ConfigureAwait(false); } } }
/// <summary> /// Sorts the move using the specified IComparer. /// The Pv move will not be effected by this sorting. /// </summary> /// <param name="comparer">The IComparer to use when comparing and sorting moves.</param> public void Sort(IComparer <Move> comparer) { m_moves.Sort(1, m_moves.Count - 1, comparer); }
static protected RangeView <TElement> FindManyClosestCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key, bool selectLower) { var closest = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, key, keySelector, comparer, selectLower); if (closest == -1) { return(RangeView <TElement> .Empty); } return(FindManyCore(indexArray, keySelector, comparer, keySelector(indexArray[closest]))); }
// Many static protected RangeView <TElement> FindManyCore <TKey>(TElement[] indexKeys, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key) { var lo = BinarySearch.LowerBound(indexKeys, 0, indexKeys.Length, key, keySelector, comparer); if (lo == -1) { return(RangeView <TElement> .Empty); } var hi = BinarySearch.UpperBound(indexKeys, 0, indexKeys.Length, key, keySelector, comparer); if (hi == -1) { return(RangeView <TElement> .Empty); } return(new RangeView <TElement>(indexKeys, lo, hi, true)); }
// Optimize for IntKey static protected TElement FindUniqueCoreInt(TElement[] indexArray, Func <TElement, int> keySelector, IComparer <int> _, int key) { var index = BinarySearch.FindFirstIntKey(indexArray, key, keySelector); return((index != -1) ? indexArray[index] : default(TElement)); }
// Util protected TElement[] CloneAndSortBy <TKey>(Func <TElement, TKey> indexSelector, IComparer <TKey> comparer) { var array = new TElement[data.Length]; var sortSource = new TKey[data.Length]; for (int i = 0; i < data.Length; i++) { array[i] = data[i]; sortSource[i] = indexSelector(data[i]); } Array.Sort(sortSource, array, 0, array.Length, comparer); return(array); }
static protected TElement FindUniqueClosestCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key, bool selectLower) { var index = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, key, keySelector, comparer, selectLower); return((index != -1) ? indexArray[index] : default(TElement)); }
/// <summary> /// Creates a new historical scheduler with the specified initial clock value. /// </summary> /// <param name="initialClock">Initial value for the clock.</param> /// <param name="comparer">Comparer to determine causality of events based on absolute time.</param> /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is <c>null</c>.</exception> public HistoricalScheduler(DateTimeOffset initialClock, IComparer <DateTimeOffset> comparer) : base(initialClock, comparer) { }
// Unique static protected TElement FindUniqueCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key) { var index = BinarySearch.FindFirst(indexArray, key, keySelector, comparer); return((index != -1) ? indexArray[index] : default(TElement)); }
/// <summary> /// Sorts the specified action. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">The action.</param> /// <param name="id">The id.</param> /// <param name="comparer">The comparer.</param> /// <returns></returns> public static IEnumerable <T> Sort <T>(Func <int, IEnumerable <T> > action, int id, IComparer <T> comparer) => action(id).Sort(comparer.Compare);
static protected RangeView <TElement> FindManyRangeCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey min, TKey max, bool ascendant) { var lo = FindManyClosestCore(indexArray, keySelector, comparer, min, false).FirstIndex; var hi = FindManyClosestCore(indexArray, keySelector, comparer, max, true).LastIndex; return(new RangeView <TElement>(indexArray, lo, hi, ascendant)); }
public ActionResult SortByLikes(string userName) { _currentPage = 0; _currentComparer = new LikeComparer(); return(PartialView("_DisplayVideos", GetItemsPage(userName, _currentComparer).Videos.ToList())); }
/// <summary> /// Creates a new historical scheduler with the specified initial clock value and absolute time comparer. /// </summary> /// <param name="initialClock">Initial value for the clock.</param> /// <param name="comparer">Comparer to determine causality of events based on absolute time.</param> protected HistoricalSchedulerBase(DateTimeOffset initialClock, IComparer <DateTimeOffset> comparer) : base(initialClock, comparer) { }
/// <summary> /// Returns the item with the minimum value in a sequence of values. /// </summary> /// <typeparam name="TSource">The type of the elements of source.</typeparam> /// <typeparam name="TKey">The type of the elements of selector.</typeparam> /// <param name="source">A sequence of values to determine the minimum value of.</param> /// <param name="selector">A delegate used to select the values</param> /// <param name="comparer"> /// A comparer used to compare the value defined by <typeparamref name="TKey"/> /// </param> /// <returns>The minimum value in the sequence</returns> public static TSource MinBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> selector, IComparer <TKey> comparer) { // https://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value if (source == null) { throw new ArgumentNullException("source"); } if (selector == null) { throw new ArgumentNullException("selector"); } comparer = comparer ?? Comparer <TKey> .Default; using (var sourceIterator = source.GetEnumerator()) { if (!sourceIterator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } var min = sourceIterator.Current; var minKey = selector(min); while (sourceIterator.MoveNext()) { var candidate = sourceIterator.Current; var candidateProjected = selector(candidate); if (comparer.Compare(candidateProjected, minKey) < 0) { min = candidate; minKey = candidateProjected; } } return(min); } }
/// <summary> /// Sorts the specified action. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">The action.</param> /// <param name="comparer">The comparer.</param> /// <returns></returns> public static IEnumerable <T> Sort <T>(Func <IEnumerable <T> > action, IComparer <T> comparer) => action().Sort(comparer.Compare);
public static void Sort <T, TValue>(this List <T> source, Func <T, TValue> selector, IComparer <TValue> comparer, bool descending) { if (source == null) { throw new ArgumentNullException("source"); } if (comparer == null) { comparer = Comparer <TValue> .Default; } var itemComparer = new ProjectionComparer <T, TValue>(selector, comparer); source.Sort(descending ? itemComparer.Reverse() : itemComparer); }
public static void SetCustomSorter(DependencyObject obj, IComparer value) { obj.SetValue(CustomSorterProperty, value); }
/// <summary> /// Sorts the array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(IComparer<T> comparer) { Array.Sort(this.elements, 0, this.Count, new Comparer(comparer)); }
public BinaryHeap(IComparer <T> comparer) { Comparer = comparer; collection = CreateCollection(); }
public static IAsyncObserver <TSource> MaxBy <TSource, TKey>(IAsyncObserver <IList <TSource> > observer, Func <TSource, TKey> keySelector, IComparer <TKey> comparer) { if (observer == null) { throw new ArgumentNullException(nameof(observer)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } if (comparer == null) { throw new ArgumentNullException(nameof(comparer)); } return(MaxBy(observer, x => Task.FromResult(keySelector(x)), comparer)); }
internal Comparer(IComparer<T> comparer = null) { Requires.NotNull(comparer, "comparer"); this.comparer = comparer; }
public static IAsyncObserver <TSource> MaxBy <TSource, TKey>(IAsyncObserver <IList <TSource> > observer, Func <TSource, Task <TKey> > keySelector, IComparer <TKey> comparer) { if (observer == null) { throw new ArgumentNullException(nameof(observer)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } if (comparer == null) { throw new ArgumentNullException(nameof(comparer)); } var hasValue = false; var lastKey = default(TKey); var list = new List <TSource>(); return(Create <TSource>( async x => { var key = default(TKey); try { key = await keySelector(x).ConfigureAwait(false); } catch (Exception ex) { await observer.OnErrorAsync(ex).ConfigureAwait(false); return; } var comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer.Compare(key, lastKey); } catch (Exception ex) { await observer.OnErrorAsync(ex).ConfigureAwait(false); return; } } if (comparison > 0) { lastKey = key; list.Clear(); } if (comparison >= 0) { list.Add(x); } }, observer.OnErrorAsync, async() => { await observer.OnNextAsync(list).ConfigureAwait(false); await observer.OnCompletedAsync().ConfigureAwait(false); } )); }
public IntersectAsyncIterator(IEnumerable <IAsyncEnumerable <TSource> > sources, int?limit, Func <TSource, TKey> keySelector, Func <TSource, TResult> resultSelector, IComparer <TKey> comparer) : base(sources, limit, keySelector, resultSelector, comparer) { }
public static OrderedEnumerableRowCollection <TRow> OrderBy <TRow, TKey> (this EnumerableRowCollection <TRow> source, Func <TRow, TKey> keySelector, IComparer <TKey> comparer) { return(OrderedEnumerableRowCollection <TRow> .Create <TRow, TKey> (source, keySelector, comparer, false)); }
public static IAsyncObservable <IList <TSource> > MaxBy <TSource, TKey>(IAsyncObservable <TSource> source, Func <TSource, Task <TKey> > keySelector, IComparer <TKey> comparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } if (comparer == null) { throw new ArgumentNullException(nameof(comparer)); } return(Create <IList <TSource> >(observer => source.SubscribeSafeAsync(AsyncObserver.MaxBy(observer, keySelector, comparer)))); }
/// <summary> /// Instantiate a new Priority Queue /// </summary> /// <param name="comparer">The comparer used to compare TPriority values. Defaults to Comparer<TPriority>.default</param> public SimplePriorityQueue(IComparer <TPriority> comparer) : this(comparer.Compare) { }
public static OrderedEnumerableRowCollection <TRow> ThenByDescending <TRow, TKey> (this OrderedEnumerableRowCollection <TRow> source, Func <TRow, TKey> keySelector, IComparer <TKey> comparer) { return(OrderedEnumerableRowCollection <TRow> .AddSort <TRow, TKey> (source, keySelector, comparer, true)); }