// // ExtensionMethods.cs - implements generic-typed extension methods for System.Collections classes // // Author: // Michael Becker // // Copyright (c) 2020 Mike Becker's Software // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . using System; using System.Collections.Generic; namespace MBS.Framework.Collections.Generic { public static class ExtensionMethods { private static Dictionary> cacheOfT = new Dictionary>(); /// /// Returns an array of type which consists of all elements in the specified that are of type /// . /// /// An array of type which consists of all elements in the specified that are of type /// . /// A containing the elements to search. /// A type parameter indicating the type of elements to retrieve. public static T[] OfType(this System.Collections.IList obj) { if (!cacheOfT.ContainsKey(obj)) { cacheOfT[obj] = new Dictionary(); } if (!cacheOfT[obj].ContainsKey(typeof(T))) { List list = new List(); for (int i = 0; i < obj.Count; i++) { if (obj[i] is T) { list.Add((T)obj[i]); } } cacheOfT[obj][typeof(T)] = list; } return ((List)(cacheOfT[obj][typeof(T)])).ToArray(); } public static void AddRange(this IList list, IEnumerable items) { foreach (T item in items) { list.Add(item); } } public static T[] ToNullTerminatedArray(this IEnumerable enumerable) where T : class { List list = new List(); foreach (T name in enumerable) { list.Add(name); } list.Add(null); return list.ToArray(); } } }