12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Bowin.Common.Utility
- {
- public static class EnumerableEx
- {
- public static void ForEach<T>(this IEnumerable<T> sources, Action<T> action)
- {
- foreach (var item in sources)
- {
- action(item);
- }
- }
- public static void ForEach<T>(this IEnumerable<T> sources, Action<T, int> action)
- {
- var index = 0;
- foreach (var item in sources)
- {
- action(item, index++);
- }
- }
- public static void ForEach<T, K>(this IEnumerable<T> sources, Func<T, K> action)
- {
- foreach (var item in sources)
- {
- action(item);
- }
- }
- public static string ToStringEx<T>(this IEnumerable<T> enumerable, string separator)
- {
- return string.Join(separator, enumerable);
- }
- public static string ToStringEx<T>(this IEnumerable<string> enumerable, string separator)
- {
- return string.Join(separator, enumerable);
- }
- public static List<string> MergeInt(this IEnumerable<int?> enumerable, string separator = "-")
- {
- return enumerable.Where(x => x.HasValue).Select(x => x.Value).ToList().MergeInt(separator);
- }
- public static List<string> MergeInt(this IEnumerable<int> enumerable, string separator = "-")
- {
- List<string> result = new List<string>();
- var orderedEnumerable = enumerable.OrderBy(x => x);
- var numberCount = orderedEnumerable.Count();
- if (numberCount == 0) return new List<string>();
- int firstNum = orderedEnumerable.First();
- int lastNum = orderedEnumerable.First();
- for (int i = 1; i < numberCount; i++)
- {
- var curNum = orderedEnumerable.ElementAt(i);
- if (curNum > (lastNum + 1))
- {
- if (firstNum == lastNum)
- {
- result.Add(firstNum.ToString());
- }
- else
- {
- result.Add(firstNum.ToString() + separator + lastNum.ToString());
- }
- firstNum = curNum;
- }
- lastNum = curNum;
- }
- if (firstNum == lastNum)
- {
- result.Add(firstNum.ToString());
- }
- else
- {
- result.Add(firstNum.ToString() + separator + lastNum.ToString());
- }
- return result;
- }
- }
- }
|