Created
November 26, 2015 09:27
-
-
Save TangChr/26426f230b21c905e556 to your computer and use it in GitHub Desktop.
C#: Array Extension Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
namespace TangChr | |
{ | |
static class ArrayExtensions | |
{ | |
public static TSource[] Remove<TSource>(this TSource[] source, TSource item) | |
{ | |
var result = new TSource[source.Length - source.Count(s => s.Equals(item))]; | |
var x = 0; | |
foreach (var i in source.Where(i => !Equals(i, item))) | |
{ | |
result[x] = i; | |
x++; | |
} | |
return result; | |
} | |
public static TSource[] RemoveAt<TSource>(this TSource[] source, int index) | |
{ | |
var result = new TSource[source.Length - 1]; | |
var x = 0; | |
for (var i = 0; i < source.Length; i++) | |
{ | |
if (i == index) continue; | |
result[x] = source[i]; | |
x++; | |
} | |
return result; | |
} | |
public static TSource[] RemoveAll<TSource>(this TSource[] source, Predicate<TSource> predicate) | |
{ | |
var result = new TSource[source.Length - source.Count(s => predicate(s))]; | |
var i = 0; | |
foreach (var item in source.Where(item => !predicate(item))) | |
{ | |
result[i] = item; | |
i++; | |
} | |
return result; | |
} | |
public static void ForEach<TSource>(this TSource[] source, Action<TSource> action) | |
{ | |
foreach (var item in source) | |
action(item); | |
} | |
public static void ForEach<TSource>(this TSource[] source, Action<TSource> action, Func<TSource, bool> predicate) | |
{ | |
foreach (var item in source.Where(predicate)) | |
action(item); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment