From a2aedd19bb1d159137fc6aa864428b57fedce99d Mon Sep 17 00:00:00 2001 From: Krzysztof Jafra Date: Wed, 13 Jun 2018 12:07:19 +0200 Subject: [PATCH 1/4] New ICollection extension method - Swap --- .../ICollection[T].Swap.cs | 42 +++++++++++++++++++ src/Z.Collections/Z.Collections.csproj | 2 + .../ICollection[T].Swap.cs | 38 +++++++++++++++++ .../Z.Collections.Test.csproj | 1 + 4 files changed, 83 insertions(+) create mode 100644 src/Z.Collections/System.Collections.Generic.ICollection[T]/ICollection[T].Swap.cs create mode 100644 test/Z.Collections.Test/System.Collections.Generic.ICollection[T]/ICollection[T].Swap.cs diff --git a/src/Z.Collections/System.Collections.Generic.ICollection[T]/ICollection[T].Swap.cs b/src/Z.Collections/System.Collections.Generic.ICollection[T]/ICollection[T].Swap.cs new file mode 100644 index 00000000..53c4df1d --- /dev/null +++ b/src/Z.Collections/System.Collections.Generic.ICollection[T]/ICollection[T].Swap.cs @@ -0,0 +1,42 @@ +// Description: C# Extension Methods Library to enhances the .NET Framework by adding hundreds of new methods. It drastically increases developers productivity and code readability. Support C# and VB.NET +// Website & Documentation: https://github.com/zzzprojects/Z.ExtensionMethods +// Forum: https://github.com/zzzprojects/Z.ExtensionMethods/issues +// License: https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE +// More projects: http://www.zzzprojects.com/ +// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. +using System; +using System.Collections.Generic; + +public static partial class Extensions +{ + /// + /// An ICollection<T> extension method that swaps value only when it exists in a collection. + /// + /// Generic type parameter. + /// The @this to act on. + /// The old value. + /// The new value. + /// + /// true if it succeeds, false if it fails. + /// + public static ICollection Swap(this ICollection @this, T oldValue, T newValue) + { + var collectionAsList = @this as IList; + + if (collectionAsList != null) + { + var oldIndex = collectionAsList.IndexOf(oldValue); + + if(oldIndex < 0) + return collectionAsList; + + collectionAsList.RemoveAt(oldIndex); + collectionAsList.Insert(oldIndex, newValue); + return collectionAsList; + } + + @this.Remove(oldValue); + @this.Add(newValue); + return @this; + } +} \ No newline at end of file diff --git a/src/Z.Collections/Z.Collections.csproj b/src/Z.Collections/Z.Collections.csproj index da9e6830..39881676 100644 --- a/src/Z.Collections/Z.Collections.csproj +++ b/src/Z.Collections/Z.Collections.csproj @@ -63,6 +63,7 @@ + @@ -102,6 +103,7 @@ +