using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Tango.Core; /// /// Contains extension methods. /// public static class IEnumerableExtensions { /// /// Creates a new observable collection from the specified enumerable. /// /// /// The enumerable. /// public static ObservableCollection ToObservableCollection(this IEnumerable enumerable) { return new ObservableCollection(enumerable); } /// /// Creates a new synchronized observable collection from the specified enumerable. /// /// /// The enumerable. /// public static SynchronizedObservableCollection ToSynchronizedObservableCollection(this IEnumerable enumerable) { return new SynchronizedObservableCollection(enumerable); } /// /// Creates a new read-only collection from the specified enumerable. /// /// /// The enumerable. /// public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable enumerable) { return new ReadOnlyCollection(enumerable.ToList()); } /// /// Replace an element in the array. /// /// /// The items. /// The condition. /// The replace action. /// public static IEnumerable Replace(this IEnumerable items, Predicate condition, Func replaceAction) { return items.Select(item => condition(item) ? replaceAction(item) : item); } /// /// Returns the closest double number in the array. /// /// The items. /// The source. /// public static double Closest(this IEnumerable items, double source) { double closest = items.Aggregate((x, y) => Math.Abs(x - source) < Math.Abs(y - source) ? x : y); return closest; } /// /// Takes the last n elements from the list.. /// /// /// The source. /// The n. /// public static IEnumerable TakeLast(this IEnumerable source, int N) { return source.Skip(Math.Max(0, source.Count() - N)); } /// /// Joins the list items ToString outputs to a single string using the specified separator. /// /// /// The source. /// The separator. /// public static String Join(this IEnumerable source, String separator) { return String.Join(separator, source); } /// /// Returns a distinct collection by the specified property. /// /// /// The source. /// The property. /// public static IEnumerable DistinctBy(this IEnumerable source, Func property) { return source.GroupBy(property).Select(g => g.First()); } /// /// Orders the collection by natural alphanumeric string. /// /// /// The source. /// The selector. /// public static IOrderedEnumerable OrderByAlphaNumeric(this IEnumerable source, Func selector) { int max = source .SelectMany(i => Regex.Matches(selector(i), @"\d+").Cast().Select(m => (int?)m.Value.Length)) .Max() ?? 0; return source.OrderBy(i => Regex.Replace(selector(i), @"\d+", m => m.Value.PadLeft(max, '0'))); } }