// Copyright Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Text; namespace EpicGames.Core { /// /// Extension methods for /// public static class EnumerableExtensions { /// /// Split the sequence into batches of at most the given size /// /// The element type /// Sequence to split into batches /// Maximum size of each batch /// Sequence of batches public static IEnumerable> Batch(this IEnumerable Sequence, int BatchSize) { List Elements = new List(BatchSize); foreach (TElement Element in Sequence) { Elements.Add(Element); if (Elements.Count == BatchSize) { yield return Elements; Elements.Clear(); } } if (Elements.Count > 0) { yield return Elements; } } /// /// Finds the minimum element by a given field /// /// /// /// /// public static TElement MinBy(this IEnumerable Sequence, Func Selector) { IEnumerator Enumerator = Sequence.GetEnumerator(); if (!Enumerator.MoveNext()) { throw new Exception("Collection is empty"); } TElement MinElement = Enumerator.Current; int MinValue = Selector(MinElement); while (Enumerator.MoveNext()) { int Value = Selector(Enumerator.Current); if (Value < MinValue) { MinElement = Enumerator.Current; } } return MinElement; } /// /// Finds the maximum element by a given field /// /// /// /// /// public static TElement MaxBy(this IEnumerable Sequence, Func Selector) { IEnumerator Enumerator = Sequence.GetEnumerator(); if (!Enumerator.MoveNext()) { throw new Exception("Collection is empty"); } TElement MaxElement = Enumerator.Current; int MaxValue = Selector(MaxElement); while (Enumerator.MoveNext()) { int Value = Selector(Enumerator.Current); if (Value > MaxValue) { MaxElement = Enumerator.Current; } } return MaxElement; } } }