using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace Kit.Helpers { public static class SystemCollectionExtensionMethods { public static IList NullToEmpty(this IList list) { return list ?? new List(); } public static IEnumerable NullToEmpty(this IEnumerable list) { return list ?? new List(); } public static IList AddRange(this IList list, IEnumerable items) { if (items == null) return list; foreach (TItem item in items) list.Add(item); return list; } public static IList AddRangeEx(this IList list, IEnumerable items) { if (items == null) return list; foreach (TItem item in items) list.Add(item); return list; } public static IList AddEx(this IList list, TItem item) { list.Add(item); return list; } public static IEnumerable AddToNewList(this IEnumerable list, TItem item) { return list.ToList().AddEx(item); } public static IDictionary AddRange(this IDictionary target, IDictionary source) { foreach (var item in source) target.SetByKey(item.Key, item.Value); return target; } public static bool IsNullOrEmpty(this IEnumerable collection) { return (collection == null || !collection.Any()); } public static TValue GetByKey(this IDictionary dictionary, TKey key, TValue defaultValue) { return dictionary != null && dictionary.ContainsKey(key) ? dictionary[key] : defaultValue; } public static TValue GetByKey(this IDictionary dictionary, TKey key) { return dictionary.GetByKey(key, default(TValue)); } public static TValue SetByKey(this IDictionary dictionary, TKey key, TValue value) { if (dictionary == null) throw new ArgumentNullException("dictionary"); lock (dictionary) { if (!dictionary.ContainsKey(key)) dictionary.Add(key, value); else dictionary[key] = value; } return value; } public static object CastToTypedEnumerable(this IEnumerable collection, Type targetType) { var resultListType = typeof(List<>).MakeGenericType(targetType); var resultList = (IList)Activator.CreateInstance(resultListType); foreach (var collectionItem in collection) resultList.Add(collectionItem); return resultList; } public static Dictionary ParseToDictionaryString(this NameValueCollection collection) { Dictionary result = new Dictionary(); foreach (string item in collection.Keys) { result.Add(item, collection[item]); } return result; } public static string ParseToString(this NameValueCollection collection, char parameterSeparator, char nameValueSeparator) { StringBuilder sb = new StringBuilder(); foreach (string item in collection.Keys) { sb.AppendFormat("{0}{1}{2}{3}",item,nameValueSeparator,collection[item],parameterSeparator); } return sb.ToString(); } public static void Add(this NameValueCollection collection, IEnumerable> items) { foreach (KeyValuePair kv in items) { if (Equals(kv.Key, default(TKey))) continue; string value = Equals(kv.Value, default(TValue)) ? string.Empty : kv.Value.ToString(); collection.Add(kv.Key.ToString(), value); } } public static NameValueCollection ToNameValueCollection(this IEnumerable> kvpCollection) { NameValueCollection collection = new NameValueCollection(); collection.Add(kvpCollection); return collection; } public static string Join(this string[] array, string separator) { return string.Join(separator, array); } public static string Join(this string[] array) { return array.Join(","); } public static string Join(this IEnumerable collection, string separator) { if (collection == null) return null; IEnumerable stringCollection = collection.Select(x => x.ToString()); //(from o in collection // where Equals(o, default(TObject)) // select o.ToString()); return stringCollection.ToArray().Join(separator); } public static string Join(this IEnumerable collection) { return collection.Join(","); } public static IEnumerable> ToKeyValuePairs(this NameValueCollection nvc) { List> kvc = new List>(); if (nvc == null) return kvc; foreach(string key in nvc.Keys) kvc.Add(new KeyValuePair(key, nvc[key])); return kvc; } public static IEnumerable Random(this IEnumerable collection, int limit = -1) { if (collection == null) return null; var random = new Random(); collection = collection.OrderBy(o => random.Next()); if (limit > -1) collection = collection.Take(limit); return collection; } public static IEnumerable ForEach(this IEnumerable collection, Action action) { if (collection == null) return null; if (action == null) return collection; IEnumerable forEach = collection as IList ?? collection.ToList(); foreach (T element in forEach) action(element); return forEach; } public static IEnumerable InsertFirstToNewList(this IEnumerable list, TItem item) { var lists = list.ToList(); lists.Insert(0, item); return lists; } public static List SearchBytePattern(this byte[] Source, byte[] Pattern, int Start) { int SourceLen = Source.Length - Pattern.Length + 1;//Получаем длину исходного массива. int j; var positions = new List();//Переменная для хранения списка результатов поиска. for (int i = Start; i < SourceLen; i++) { if (Source[i] != Pattern[0]) continue;//Сравниваем первый искомый байт и если он совпадает, то проверяем остальные байты за ним идущие, иначе идем дальше по массиву. for (j = Pattern.Length - 1; j >= 1 && Source[i + j] == Pattern[j]; j--) ;//Сравниваем остальные байты с нашим значением. if (j == 0)//Переменная будет равна нулю, если все байты совпали { positions.Add(i);//Добавляем адрес конца совпадения первого байта в список i += Pattern.Length - 1;//Увеличиваем значение переменной на величину искомого, так как мы его уже проверили и это ускоряет поиск. } } return positions;//Отдаем список адресов, которые совпадают с искомым значением. } public static bool IsEnumerable(this object obj) { return typeof(IEnumerable).IsAssignableFrom(obj.GetType()); } public static bool IsList(this object obj) { return typeof(IList).IsAssignableFrom(obj.GetType()); } } }