From c507fe4f836794104e9bb57d4fb2ac527a803f46 Mon Sep 17 00:00:00 2001 From: Michael Becker Date: Fri, 20 Nov 2020 22:19:43 -0500 Subject: [PATCH] add OfType extension method to IList --- .../Collections/Generic/ExtensionMethods.cs | 58 +++++++++++++++++++ MBS.Framework/MBS.Framework.csproj | 1 + 2 files changed, 59 insertions(+) create mode 100644 MBS.Framework/Collections/Generic/ExtensionMethods.cs diff --git a/MBS.Framework/Collections/Generic/ExtensionMethods.cs b/MBS.Framework/Collections/Generic/ExtensionMethods.cs new file mode 100644 index 0000000..0f2c7f9 --- /dev/null +++ b/MBS.Framework/Collections/Generic/ExtensionMethods.cs @@ -0,0 +1,58 @@ +// +// 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(); + } + } +} diff --git a/MBS.Framework/MBS.Framework.csproj b/MBS.Framework/MBS.Framework.csproj index 443afa5..73ad8c1 100644 --- a/MBS.Framework/MBS.Framework.csproj +++ b/MBS.Framework/MBS.Framework.csproj @@ -86,6 +86,7 @@ +