IEnumerableExtension.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. public static class IEnumerableExtension
  8. {
  9. #region Get random element from list
  10. public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
  11. {
  12. var random = new System.Random();
  13. var indexList = new List<int>();
  14. for (int i = 0; i < list.ToList().Count; i++)
  15. {
  16. indexList.Add(i);
  17. }
  18. for (int i = 0; i < count; i++)
  19. {
  20. int index = random.Next(0, indexList.Count);
  21. int value = indexList[index];
  22. indexList.RemoveAt(index);
  23. yield return list.ToList()[value];
  24. }
  25. }
  26. #endregion
  27. #region Map
  28. public static List<U> Map<T, U>(this List<T> list, Func<T, U> getElement)
  29. {
  30. return list.Select(x => getElement(x)).ToList();
  31. }
  32. public static U[] Map<T, U>(this T[] array, Func<T, U> getElement)
  33. {
  34. return array.Select(x => getElement(x)).ToArray();
  35. }
  36. #endregion
  37. #region Filter
  38. public static List<T> Filter<T>(this List<T> list, Func<T, bool> getElement)
  39. {
  40. return list.Where(x => getElement(x)).ToList();
  41. }
  42. public static T[] Filter<T>(this T[] array, Func<T, bool> getElement)
  43. {
  44. return array.Where(x => getElement(x)).ToArray();
  45. }
  46. #endregion
  47. #region Some
  48. public static bool Some<T>(this IEnumerable<T> list, Func<T, bool> getElement)
  49. {
  50. return list.Any(x => getElement(x));
  51. }
  52. #endregion
  53. #region Flat
  54. public static List<T> Flat<T>(this List<List<T>> list)
  55. {
  56. return list.SelectMany(x => x).ToList();
  57. }
  58. public static T[] Flat<T>(this T[][] array)
  59. {
  60. return array.SelectMany(x => x).ToArray();
  61. }
  62. #endregion
  63. #region Reduce
  64. public static T Reduce<T>(this IEnumerable<T> list, Func<T, T, T> getResult)
  65. {
  66. return list.Aggregate(getResult);
  67. }
  68. #endregion
  69. #region Clone
  70. public static List<T> Clone<T>(this List<T> list)
  71. {
  72. return list.Map(x => x).ToList();
  73. }
  74. public static T[] CloneArray<T>(this T[] array)
  75. {
  76. return array.Map(x => x).ToArray();
  77. }
  78. #endregion
  79. #region Every
  80. public static bool Every<T>(this IEnumerable<T> list, Func<T, bool> getElement)
  81. {
  82. return list.All(x => getElement(x));
  83. }
  84. #endregion
  85. }