EnumerableEx.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Bowin.Common.Utility
  6. {
  7. public static class EnumerableEx
  8. {
  9. public static void ForEach<T>(this IEnumerable<T> sources, Action<T> action)
  10. {
  11. foreach (var item in sources)
  12. {
  13. action(item);
  14. }
  15. }
  16. public static void ForEach<T>(this IEnumerable<T> sources, Action<T, int> action)
  17. {
  18. var index = 0;
  19. foreach (var item in sources)
  20. {
  21. action(item, index++);
  22. }
  23. }
  24. public static void ForEach<T, K>(this IEnumerable<T> sources, Func<T, K> action)
  25. {
  26. foreach (var item in sources)
  27. {
  28. action(item);
  29. }
  30. }
  31. public static string ToStringEx<T>(this IEnumerable<T> enumerable, string separator)
  32. {
  33. return string.Join(separator, enumerable);
  34. }
  35. public static string ToStringEx<T>(this IEnumerable<string> enumerable, string separator)
  36. {
  37. return string.Join(separator, enumerable);
  38. }
  39. public static List<string> MergeInt(this IEnumerable<int?> enumerable, string separator = "-")
  40. {
  41. return enumerable.Where(x => x.HasValue).Select(x => x.Value).ToList().MergeInt(separator);
  42. }
  43. public static List<string> MergeInt(this IEnumerable<int> enumerable, string separator = "-")
  44. {
  45. List<string> result = new List<string>();
  46. var orderedEnumerable = enumerable.OrderBy(x => x);
  47. var numberCount = orderedEnumerable.Count();
  48. if (numberCount == 0) return new List<string>();
  49. int firstNum = orderedEnumerable.First();
  50. int lastNum = orderedEnumerable.First();
  51. for (int i = 1; i < numberCount; i++)
  52. {
  53. var curNum = orderedEnumerable.ElementAt(i);
  54. if (curNum > (lastNum + 1))
  55. {
  56. if (firstNum == lastNum)
  57. {
  58. result.Add(firstNum.ToString());
  59. }
  60. else
  61. {
  62. result.Add(firstNum.ToString() + separator + lastNum.ToString());
  63. }
  64. firstNum = curNum;
  65. }
  66. lastNum = curNum;
  67. }
  68. if (firstNum == lastNum)
  69. {
  70. result.Add(firstNum.ToString());
  71. }
  72. else
  73. {
  74. result.Add(firstNum.ToString() + separator + lastNum.ToString());
  75. }
  76. return result;
  77. }
  78. }
  79. }