-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEnumerableExtensions.cs
More file actions
481 lines (427 loc) · 19.7 KB
/
EnumerableExtensions.cs
File metadata and controls
481 lines (427 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
namespace System.Collections.Generic;
public static class EnumerableExtensions
{
/// <summary>
/// Same as <see cref="Enumerable.Aggregate{TSource}"/>, but keeps the same <paramref name="seed"/> so the <paramref
/// name="action"/> doesn't have to return anything.
/// </summary>
/// <param name="source">The collection to traverse.</param>
/// <param name="seed">The object to pass to <paramref name="action"/> during enumeration.</param>
/// <param name="action">The action called on each item of <paramref name="source"/>.</param>
/// <typeparam name="TSource">The type of the items in <paramref name="source"/>.</typeparam>
/// <typeparam name="TAccumulate">The type of the <paramref name="seed"/>.</typeparam>
/// <returns>The instance passed to <paramref name="seed"/>.</returns>
public static TAccumulate AggregateSeed<TSource, TAccumulate>(
this IEnumerable<TSource> source,
TAccumulate seed,
Action<TAccumulate, TSource> action)
where TAccumulate : class =>
source.Aggregate(
seed,
(seed, item) =>
{
action(seed, item);
return seed;
});
/// <summary>
/// Executes <paramref name="action"/> on every item of the <paramref name="source"/>. This eliminates the need for
/// code like <c>if (source.Any()) { beforeFirst(); foreach (var item in source) { ... } }</c> which cause multiple
/// enumeration unless first converted into an <see cref="ICollection{T}"/> (which takes additional allocations).
/// </summary>
/// <param name="source">The collection to traverse with single enumeration.</param>
/// <param name="action">The action to perform on each item of <paramref name="source"/>.</param>
/// <param name="beforeFirst">The action to perform before the first item's <paramref name="action"/>.</param>
/// <typeparam name="T">The type of the items in <paramref name="source"/>.</typeparam>
/// <returns><see langword="true"/> if the <paramref name="source"/> had at least one item.</returns>
public static bool ForEach<T>(this IEnumerable<T> source, Action<T> action, Action<T>? beforeFirst = null)
{
bool any = false;
foreach (var item in source)
{
if (!any && beforeFirst != null) beforeFirst(item);
any = true;
action(item);
}
return any;
}
/// <summary>
/// Awaits the tasks sequentially. An alternative to <see cref="Task.WhenAll(IEnumerable{Task})"/> and
/// <c>Nito.AsyncEx.TaskExtensions.WhenAll</c> when true multi-threaded asynchronicity is not desirable.
/// </summary>
/// <param name="source">A collection of items.</param>
/// <param name="asyncOperation">An <see langword="async"/> function to call on each item.</param>
/// <typeparam name="TItem">The type of the input collection's items.</typeparam>
/// <typeparam name="TResult">The type of the output collection's items.</typeparam>
/// <returns>When awaited, the <see cref="Task"/> that contains the results which were added one-by-one.</returns>
public static async Task<IList<TResult>> AwaitEachAsync<TItem, TResult>(
this IEnumerable<TItem> source,
Func<TItem, Task<TResult>> asyncOperation)
{
var results = new List<TResult>();
foreach (var item in source) results.Add(await asyncOperation(item));
return results;
}
/// <inheritdoc cref="AwaitEachAsync{TItem,TResult}(IEnumerable{TItem},Func{TItem,Task{TResult}})"/>
public static async Task<IList<TResult>> AwaitEachAsync<TItem, TResult>(
this IEnumerable<TItem> source,
Func<TItem, int, Task<TResult>> asyncOperation)
{
var results = new List<TResult>();
int index = 0;
foreach (var item in source) results.Add(await asyncOperation(item, index++));
return results;
}
/// <inheritdoc cref="AwaitEachAsync{TItem,TResult}(IEnumerable{TItem},Func{TItem,Task{TResult}})"/>
/// <returns>The <see cref="Task"/> that'll complete when all items have completed.</returns>
public static async Task AwaitEachAsync<TItem>(
this IEnumerable<TItem> source,
Func<TItem, Task> asyncOperation)
{
foreach (var item in source) await asyncOperation(item);
}
/// <summary>
/// Awaits the tasks sequentially while the action returns <see langword="true"/>.
/// </summary>
/// <returns><see langword="true"/> if the <see langword="foreach"/> was never broken.</returns>
public static async Task<bool> AwaitWhileAsync<TItem>(
this IEnumerable<TItem> source,
Func<TItem, Task<bool>> asyncWhileOperation)
{
foreach (var item in source)
{
if (!await asyncWhileOperation(item)) return false;
}
return true;
}
/// <summary>
/// Awaits the tasks sequentially until the action returns <see langword="true"/>.
/// </summary>
/// <returns><see langword="true"/> if the <see langword="foreach"/> was never broken.</returns>
public static async Task<bool> AwaitUntilAsync<TItem>(
this IEnumerable<TItem> source,
Func<TItem, Task<bool>> asyncUntilOperation)
{
foreach (var item in source)
{
if (await asyncUntilOperation(item)) return false;
}
return true;
}
/// <summary>
/// Determines whether any element of a sequence satisfies a condition, asynchronously, like LINQ Any().
/// </summary>
/// <returns>
/// <see langword="true"/> if any elements in the source sequence pass the test in the specified predicate;
/// otherwise, <see langword="false"/>.
/// </returns>
public static async Task<bool> AnyAsync<TItem>(
this IEnumerable<TItem> source,
Func<TItem, Task<bool>> predicate) =>
!await AwaitUntilAsync(source, predicate);
/// <summary>
/// Filters the given list by an asynchronous condition.
/// </summary>
/// <returns>Filtered list.</returns>
public static async Task<IList<TItem>> WhereAsync<TItem>(
this IEnumerable<TItem> source,
Func<TItem, Task<bool>> asyncWhereOperation)
{
var results = new List<TItem>();
foreach (var item in source)
{
if (await asyncWhereOperation(item)) results.Add(item);
}
return results;
}
/// <summary>
/// Attempts to cast <paramref name="collection"/> into <see cref="List{T}"/>. If that's not possible then converts
/// it into one. Not to be confused with <see cref="Enumerable.ToList{TSource}"/> that always creates a separate
/// <see cref="List{T}"/> regardless of source type. This extension is more suitable when the <paramref
/// name="collection"/> is expected to be <see cref="List{T}"/> but has to be stored as <see
/// cref="IEnumerable{T}"/>.
/// </summary>
public static IList<T> AsList<T>(this IEnumerable<T> collection) =>
collection is IList<T> list ? list : [.. collection];
/// <summary>
/// Transforms the specified <paramref name="collection"/> with the <paramref name="select"/> function and returns
/// the items that return <see langword="true"/> when passed to the <paramref name="where"/> function.
/// </summary>
public static IEnumerable<TOut> SelectWhere<TIn, TOut>(
this IEnumerable<TIn> collection,
Func<TIn, TOut> select,
Func<TOut, bool> where)
{
foreach (var item in collection)
{
var converted = select(item);
if (where.Invoke(converted)) yield return converted;
}
}
/// <summary>
/// Transforms the specified <paramref name="collection"/> with the <paramref name="select"/> function and returns
/// the items that are not null.
/// </summary>
public static IEnumerable<TOut> SelectWhere<TIn, TOut>(this IEnumerable<TIn> collection, Func<TIn, TOut?> select)
{
foreach (var item in collection)
{
var converted = select(item);
if (converted is not null) yield return converted;
}
}
/// <summary>
/// Returns a dictionary created from the <paramref name="collection"/>. If there are key clashes, the item later in
/// the enumeration overwrites the earlier one.
/// </summary>
[SuppressMessage(
"Design",
"MA0016:Prefer return collection abstraction instead of implementation",
Justification = "This is the point of the method.")]
public static Dictionary<TKey, TValue> ToDictionaryOverwrite<TIn, TKey, TValue>(
this IEnumerable<TIn> collection,
Func<TIn, TKey> keySelector,
Func<TIn, TValue> valueSelector)
where TKey : notnull
{
var dictionary = new Dictionary<TKey, TValue>();
foreach (var item in collection) dictionary[keySelector(item)] = valueSelector(item);
return dictionary;
}
/// <summary>
/// Returns a dictionary created from the <paramref name="collection"/>. If there are key clashes, the item later in
/// the enumeration overwrites the earlier one.
/// </summary>
[SuppressMessage(
"Design",
"MA0016:Prefer return collection abstraction instead of implementation",
Justification = "This is the point of the method.")]
public static Dictionary<TKey, TIn> ToDictionaryOverwrite<TIn, TKey>(
this IEnumerable<TIn> collection,
Func<TIn, TKey> keySelector)
where TKey : notnull =>
ToDictionaryOverwrite(collection, keySelector, item => item);
/// <summary>
/// Returns the <paramref name="collection"/> without any duplicate items.
/// </summary>
/// <remarks>
/// <para>
/// We use <see cref="Enumerable.FirstOrDefault{TSource}(IEnumerable{TSource})"/> to improve compatibility. It
/// returning <see langword="default"/> is theoretically impossible, but some DB frameworks require the "or default"
/// after grouping.
/// </para>
/// </remarks>
public static IEnumerable<TItem?> Unique<TItem, TKey>(
this IEnumerable<TItem> collection,
Func<TItem, TKey> keySelector) =>
collection.GroupBy(keySelector).Select(group => group.FirstOrDefault());
/// <summary>
/// Returns the <paramref name="collection"/> without any duplicate items picking the first of each when sorting by
/// <paramref name="orderBySelector"/>.
/// </summary>
public static IEnumerable<TItem?> Unique<TItem, TKey, TOrder>(
this IEnumerable<TItem> collection,
Func<TItem, TKey> keySelector,
Func<TItem, TOrder> orderBySelector) =>
collection
.GroupBy(keySelector)
.Select(group => group.OrderBy(orderBySelector).FirstOrDefault());
/// <summary>
/// Returns the <paramref name="collection"/> without any duplicate items picking the last of each when sorting by
/// <paramref name="orderBySelector"/>.
/// </summary>
public static IEnumerable<TItem?> UniqueDescending<TItem, TKey, TOrder>(
this IEnumerable<TItem> collection,
Func<TItem, TKey> keySelector,
Func<TItem, TOrder> orderBySelector) =>
collection
.GroupBy(keySelector)
.Select(group => group.OrderByDescending(orderBySelector).FirstOrDefault());
/// <summary>
/// Returns a string that joins the string collection. It excludes null or empty items if there are any.
/// </summary>
/// <returns>The concatenated texts if there are any nonempty, otherwise <see langword="null"/>.</returns>
public static string? JoinNotNullOrEmpty(this IEnumerable<string>? strings, string separator = ",")
{
var filteredStrings = (strings ?? [])
.Where(text => !string.IsNullOrWhiteSpace(text))
.ToList();
return filteredStrings.Count > 0
? string.Join(separator, filteredStrings)
: null;
}
/// <summary>
/// Join strings fluently.
/// </summary>
/// <param name="values">The <see cref="string"/> values to join.</param>
/// <param name="separator">The separator to use between the <paramref name="values"/>, defaults to space.</param>
/// <returns>
/// A new <see cref="string"/> that concatenates all values with the <paramref name="separator"/> provided.
/// </returns>
public static string Join(this IEnumerable<string>? values, string separator = " ") =>
string.Join(separator, values ?? []);
/// <summary>
/// A simple conditional enumeration where the items are <see langword="yield"/> ed from the <paramref
/// name="collection"/> if the <paramref name="negativePredicate"/> returns <see langword="false"/>.
/// </summary>
public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> collection, Func<T, bool> negativePredicate) =>
collection.Where(item => !negativePredicate(item));
/// <summary>
/// Filters out the <see langword="null"/> or whitespace elements of the <paramref name="collection"/>. The
/// resulting collection's elements are marked not null.
/// </summary>
public static IEnumerable<string> WhereNotNullOrWhiteSpace(this IEnumerable<string?> collection) =>
collection.WhereNot(string.IsNullOrWhiteSpace).Cast<string>();
/// <summary>
/// Filters the elements of the <paramref name="collection"/> if they return <see langword="false"/> when evaluated
/// by the <paramref name="negativePredicate"/>.
/// </summary>
public static IAsyncEnumerable<T> WhereNotAsync<T>(
this IAsyncEnumerable<T> collection,
Func<T, Task<bool>> negativePredicate) =>
collection.Where(
async (value, _) => !await negativePredicate(value));
/// <summary>
/// Returns <paramref name="collection"/> if it's not <see langword="null"/>, otherwise <see
/// cref="Enumerable.Empty{TResult}"/>.
/// </summary>
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? collection) =>
collection ?? [];
/// <summary>
/// Returns <paramref name="array"/> if it's not <see langword="null"/>, otherwise <see
/// cref="Array.Empty{TResult}"/>.
/// </summary>
public static IEnumerable<T> EmptyIfNull<T>(this T[]? array) =>
array ?? [];
/// <summary>
/// Maps the provided collection of pairs using a selector with separate arguments.
/// </summary>
public static IEnumerable<TResult> Select<TKey, TValue, TResult>(
this IEnumerable<KeyValuePair<TKey, TValue>> pairs,
Func<TKey, TValue, TResult> selector)
{
foreach (var (key, value) in pairs)
{
yield return selector(key, value);
}
}
/// <summary>
/// Maps the provided collection of pairs using a selector with separate arguments.
/// </summary>
public static IEnumerable<TResult> Select<TKey, TValue, TResult>(
this IEnumerable<(TKey Key, TValue Value)> pairs,
Func<TKey, TValue, TResult> selector)
{
foreach (var (key, value) in pairs)
{
yield return selector(key, value);
}
}
/// <summary>
/// Similar to <see cref="Enumerable.Cast{TResult}"/>, but it checks if the types are correct first, and filters out
/// the ones that couldn't be cast. The optional <paramref name="predicate"/> can filter the cast items.
/// </summary>
public static IEnumerable<T> CastWhere<T>(this IEnumerable enumerable, Func<T, bool>? predicate = null)
{
if (enumerable is IEnumerable<T> alreadyCast)
{
return predicate == null
? alreadyCast
: alreadyCast.Where(predicate);
}
static IEnumerable<T> Iterate(IEnumerable enumerable, Func<T, bool>? predicate)
{
foreach (var item in enumerable)
{
if (item is not T instance) continue;
if (predicate == null || predicate(instance)) yield return instance;
}
}
return Iterate(enumerable, predicate);
}
/// <summary>
/// Returns a copy of <paramref name="rangeCollection"/> without overlapping ranges. It prefers ranges with lower
/// starting index and higher length in that order.
/// </summary>
public static IList<Range> WithoutOverlappingRanges(
this IEnumerable<Range> rangeCollection,
bool isSortedByStart = false)
{
var ranges = rangeCollection.ToList();
if (!isSortedByStart) ranges.Sort((left, right) => left.Start.Value - right.Start.Value);
for (int currentIndex = 0; currentIndex < ranges.Count - 1; currentIndex++)
{
var current = ranges[currentIndex];
int followingIndex = currentIndex + 1;
while (followingIndex < ranges.Count && ranges[followingIndex].Start.Value < current.End.Value)
{
var following = ranges[followingIndex];
ranges.RemoveAt(
current.Start.Value == following.Start.Value && current.End.Value < following.End.Value
? currentIndex
: followingIndex);
}
}
return ranges;
}
/// <summary>
/// If the <paramref name="enumerable"/> is not empty, invokes the <paramref name="actionAsync"/> on the first item.
/// </summary>
public static Task InvokeFirstOrCompletedAsync<T>(this IEnumerable<T> enumerable, Func<T, Task> actionAsync) =>
enumerable.FirstOrDefault() is { } item
? actionAsync(item)
: Task.CompletedTask;
/// <summary>
/// If the <paramref name="enumerable"/> is not empty, invokes the <paramref name="funcAsync"/> on the first item
/// and returns its result, otherwise returns <see langword="default"/> for <typeparamref name="TResult"/>.
/// </summary>
public static Task<TResult?> InvokeFirstOrDefaultAsync<TItem, TResult>(
this IEnumerable<TItem> enumerable,
Func<TItem, Task<TResult?>> funcAsync) =>
enumerable.FirstOrDefault() is { } item
? funcAsync(item)
: Task.FromResult(default(TResult?));
/// <summary>
/// Splits the provided <paramref name="enumerable"/> into two.
/// </summary>
/// <param name="enumerable">The original collection to be tested.</param>
/// <param name="leftPredicate">
/// Tests each item of <paramref name="enumerable"/>. If returns <see langword="true"/>, the
/// item is added to the left collection, otherwise added to the right collection.
/// </param>
/// <typeparam name="T">The type of the items in <paramref name="enumerable"/>.</typeparam>
/// <returns>A tuple of two collections. Each item in <paramref name="enumerable"/> is in one of them.</returns>
public static (IList<T> Left, IList<T> Right) Fork<T>(
this IEnumerable<T>? enumerable,
Func<T, bool> leftPredicate)
{
var left = new List<T>();
var right = new List<T>();
if (enumerable is null) return (left, right);
foreach (var item in enumerable)
{
var target = leftPredicate(item) ? left : right;
target.Add(item);
}
return (left, right);
}
/// <summary>
/// Returns a new list of an exact <paramref name="length"/>. If the <paramref name="source"/> is longer, the first
/// items are used until the new list is filled. If the <paramref name="source"/> is shorter, the remaining items
/// are left as <see langword="default"/>.
/// </summary>
public static IList<T> TakeExactly<T>(this IEnumerable<T> source, int length)
{
var result = new T[length];
var index = 0;
foreach (var item in source)
{
if (index >= length) return result;
result[index] = item;
index++;
}
return result;
}
}