Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class EnumerableExtensions
- {
- // da usare con 'foreeach' per ottenrere l'indice
- public static IEnumerable<(T, int)> WithIndex<T>(this IEnumerable<T> items,
- int skip = 0, bool useSkipped = true)
- {
- if (skip < 0) throw new ArgumentOutOfRangeException(nameof(skip), "value not valid");
- return items.Select((value, index) => (value, useSkipped ? index : index - skip)).Skip(skip);
- }
- // foreach direttamente sull'enumeratore (es: items.ForEach(...))
- public static void ForEachWithIndex<T>(this IEnumerable<T> items,
- Action<T, int> action, int skip = 0, bool useSkipped = false)
- {
- foreach (var (value, index) in items.WithIndex(skip, useSkipped)) action.Invoke(value, index);
- }
- // applica where solo se si soddisfa la condizione
- public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> items, Func<T, bool> predicate, bool condition = true)
- {
- return condition ? items.Where(predicate) : items;
- }
- // Ottiene il conteggio oppure 0 se null
- public static int CountOrDefault<T>(this IEnumerable<T>? items, Func<T, bool>? predicate = null)
- {
- return predicate == null ?
- items?.Count() ?? 0 :
- items?.Count(predicate) ?? 0;
- }
- // Concatena stringhe
- public static string JoinString(this IEnumerable<string> items, string separator)
- => string.Join(separator, items);
- // ForEach Async
- public static async Task ForEachAsync<T>(this IEnumerable<T> enumerable,
- Func<T, Task> action, CancellationToken token = default)
- {
- foreach (var item in enumerable)
- {
- token.ThrowIfCancellationRequested();
- await action.Invoke(item).ConfigureAwait(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement