EnumerableExtensions.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Ips.Library.Basic
  6. {
  7. public static class EnumerableExtensions
  8. {
  9. public static bool IsNullOrEmpty<T>(this IEnumerable<T> @this)
  10. {
  11. return @this == null || !@this.Any();
  12. }
  13. public static bool IsNotNullOrEmpty<T>(this IEnumerable<T> @this)
  14. {
  15. return @this != null && @this.Any();
  16. }
  17. public static string JoinAsString(this IEnumerable<string> source, string separator)
  18. {
  19. return source.Any() ? string.Join(separator, source) : "";
  20. }
  21. public static string JoinAsString<T>(this IEnumerable<T> source, string separator)
  22. {
  23. return source.Any() ? string.Join(separator, source) : "";
  24. }
  25. public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, bool> predicate)
  26. {
  27. return condition
  28. ? source.Where(predicate)
  29. : source;
  30. }
  31. public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, int, bool> predicate)
  32. {
  33. return condition
  34. ? source.Where(predicate)
  35. : source;
  36. }
  37. public static IEnumerable<T> ForEach<T>(this IEnumerable<T> array, Action<T> act)
  38. {
  39. foreach (var i in array)
  40. act(i);
  41. return array;
  42. }
  43. public static IEnumerable<T> ForEach<T>(this IEnumerable arr, Action<T> act)
  44. {
  45. return arr.Cast<T>().ForEach<T>(act);
  46. }
  47. public static IEnumerable<RT> ForEach<T, RT>(this IEnumerable<T> array, Func<T, RT> func)
  48. {
  49. var list = new List<RT>();
  50. foreach (var i in array)
  51. {
  52. var obj = func(i);
  53. if (obj != null)
  54. list.Add(obj);
  55. }
  56. return list;
  57. }
  58. public static Dictionary<TKey, List<TValue>> ToDictionary<TKey, TValue>(this IEnumerable<IGrouping<TKey, TValue>> groupings)
  59. {
  60. return groupings.ToDictionary(group => group.Key, group => group.ToList());
  61. }
  62. }
  63. }