Advertisement
fcamuso

Pillole video 17

Jun 14th, 2025
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. public static class EnumerableExtensions
  2. {
  3.     // da usare con 'foreeach' per ottenrere l'indice
  4.     public static IEnumerable<(T, int)> WithIndex<T>(this IEnumerable<T> items,
  5.                                                                int skip = 0, bool useSkipped = true)
  6.     {
  7.         if (skip < 0) throw new ArgumentOutOfRangeException(nameof(skip), "value not valid");
  8.         return items.Select((value, index) => (value, useSkipped ? index : index - skip)).Skip(skip);
  9.     }
  10.  
  11.     // foreach direttamente sull'enumeratore (es: items.ForEach(...))
  12.     public static void ForEachWithIndex<T>(this IEnumerable<T> items,
  13.                                                      Action<T, int> action, int skip = 0, bool useSkipped = false)
  14.     {
  15.         foreach (var (value, index) in items.WithIndex(skip, useSkipped)) action.Invoke(value, index);
  16.     }
  17.  
  18.  
  19.     // applica where solo se si soddisfa la condizione
  20.     public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> items, Func<T, bool> predicate, bool condition = true)
  21.     {
  22.         return condition ? items.Where(predicate) : items;
  23.     }
  24.  
  25.    
  26.     // Ottiene il conteggio oppure 0 se null
  27.     public static int CountOrDefault<T>(this IEnumerable<T>? items, Func<T, bool>? predicate = null)
  28.     {
  29.         return predicate == null ?
  30.             items?.Count() ?? 0 :
  31.             items?.Count(predicate) ?? 0;
  32.     }
  33.  
  34.     // Concatena stringhe
  35.     public static string JoinString(this IEnumerable<string> items, string separator)
  36.         => string.Join(separator, items);
  37.  
  38.     // ForEach Async
  39.     public static async Task ForEachAsync<T>(this IEnumerable<T> enumerable,
  40.                                                        Func<T, Task> action, CancellationToken token = default)
  41.     {
  42.         foreach (var item in enumerable)
  43.         {
  44.             token.ThrowIfCancellationRequested();
  45.             await action.Invoke(item).ConfigureAwait(false);
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement