17 using System.Collections.Generic;
18 using System.Collections.Immutable;
19 using System.Collections.ObjectModel;
36 public static Dictionary<K, V>
ToDictionary<K, V>(
this IEnumerable<KeyValuePair<K, V>> enumerable)
38 return enumerable.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
50 return new ReadOnlyDictionary<K, V>(enumerable.ToDictionary());
63 return new HashSet<TResult>(enumerable.Select(selector));
74 public static List<TResult>
ToList<T, TResult>(
this IEnumerable<T> enumerable, Func<T, TResult> selector)
76 return enumerable.Select(selector).ToList();
87 public static TResult[]
ToArray<T, TResult>(
this IEnumerable<T> enumerable, Func<T, TResult> selector)
89 return enumerable.Select(selector).ToArray();
102 return enumerable.Select(selector).ToImmutableArray();
113 return enumerable ==
null || !enumerable.Any();
122 public static T
Median<T>(
this IEnumerable<T> enumerable)
124 var collection = enumerable.ToList();
125 return collection.OrderBy(x => x).Skip(collection.Count/2).First();
138 return collection.Select(selector).Median();
154 throw new ArgumentNullException(nameof(list));
156 if (comparer ==
null)
158 throw new ArgumentNullException(nameof(comparer));
162 var upper = list.Count - 1;
164 while (lower <= upper)
166 var middle = lower + (upper - lower) / 2;
167 var comparisonResult = comparer(value, list[middle]);
168 if (comparisonResult < 0)
172 else if (comparisonResult > 0)
194 return BinarySearch(list, value, Comparer<TItem>.Default);
207 return list.BinarySearch(value, comparer.Compare);
216 public static IEnumerable<T>
Memoize<T>(
this IEnumerable<T> enumerable)
232 public static IEnumerable<T>
Range<T>(T start, T end, Func<T, T> incrementer,
bool includeEndPoint =
false)
233 where T : IComparable
238 while (current.CompareTo(end) <= 0)
240 yield
return current;
241 current = incrementer(current);
246 while (current.CompareTo(end) < 0)
248 yield
return current;
249 current = incrementer(current);
263 public static IEnumerable<IEnumerable<T>>
GroupAdjacentBy<T>(
this IEnumerable<T> enumerable, Func<T, T, bool> grouper)
265 using (var e = enumerable.GetEnumerator())
269 var list =
new List<T> {e.Current};
270 var pred = e.Current;
273 if (grouper(pred, e.Current))
280 list =
new List<T> {e.Current};
300 if(ReferenceEquals(left, right))
304 return !left.SetEquals(right);
317 while (enumerator.MoveNext())
319 yield
return enumerator.Current;
336 return dictionary.TryGetValue(key, out obj) ? obj : defaultValue;
345 public static void DoForEach<T>(
this IEnumerable<T> source, Action<T> action)
347 foreach (var element
in source)