using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace Opsoft.NetCore.O3App.Shared { public static class IEnumerableExtensions { public static bool IsNullOrEmpty(this IEnumerable t) { return t == null || !t.Any(); } public static bool NotNullOrEmpty(this IEnumerable t) { return t != null && t.Any(); } public static IEnumerable Alternate(this IEnumerable first, IEnumerable second) { using (IEnumerator e1 = first.GetEnumerator()) using (IEnumerator e2 = second.GetEnumerator()) { while (e1.MoveNext()) { yield return e1.Current; if (e2.MoveNext()) { yield return e2.Current; } } while (e2.MoveNext()) { yield return e2.Current; } } } public static IEnumerable Add(this IEnumerable source, TSource element) { using (IEnumerator e1 = source.GetEnumerator()) { while (e1.MoveNext()) { yield return e1.Current; } } yield return element; } public static void AddIfNotNull(this List source, TSource item) { if (item != null) { source.Add(item); } } public static void AddRangeIfNotNull(this List source, IEnumerable items) { if (items != null) { source.AddRange(items.Where(i => i != null)); } } public static IEnumerable Convert(this IEnumerable source, Func convert) { Guard.ArgumentNotNull(convert, nameof(convert)); using (IEnumerator e = source.GetEnumerator()) { while (e.MoveNext()) { yield return convert(e.Current); } } } public static DataTable ToDataTable(this IEnumerable items) where T : class, new() { var table = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { Type t = prop.PropertyType.GetCoreType(); table.Columns.Add(prop.Name, t); } foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } table.Rows.Add(values); } return table; } public static string ToQueryString(this System.Collections.Specialized.NameValueCollection collection) { if (collection == null) { return string.Empty; } StringBuilder query = new StringBuilder(); foreach (string key in collection.Keys) { query.AppendFormat("&{0}={1}", key, collection[key] ?? ""); } return query.Length > 0 ? query.Remove(0, 1).ToString() : string.Empty; } public static void ForEach(this IEnumerable @this, Action action) { T[] array = @this.ToArray(); foreach (T t in array) { action(t); } } public static void ForEach(this IEnumerable @this, Action action) { if (@this == null) { return; } T[] array = @this.ToArray(); for (int i = 0; i < array.Length; i++) { action(array[i], i); } } } }