To determine whether the specified array contains specific element or not, Array.Exists can be used if the given array is one dimensional. I am attempting to implement Exists
method for multidimensional array cases.
The experimental implementation
static class MDArrayHelpers
{
public static bool Exists<T>(Array array, Predicate<T> match)
where T : unmanaged
{
if (ReferenceEquals(array, null))
{
throw new ArgumentNullException(nameof(array));
}
Type elementType = array.GetType().GetElementType();
if (!elementType.Equals(typeof(T)))
{
throw new System.InvalidOperationException();
}
foreach (var element in array)
{
if (match((T)element))
{
return true;
}
}
return false;
}
}
Test cases
Predicate<int> isOne = delegate (int number) { return number == 1; };
Predicate<int> isFour = delegate (int number) { return number == 4; };
Console.WriteLine("One dimensional case");
int[] array1 = new int[] { 1, 2, 3 };
Console.WriteLine($"Is one existed in {nameof(array1)}: {Array.Exists(array1, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array1)}: {Array.Exists(array1, isFour)}");
Console.WriteLine("");
Console.WriteLine("Two dimensional case");
int[,] array2 = { { 0, 1 }, { 2, 3 } };
Console.WriteLine($"Is one existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array2)}: {MDArrayHelpers.Exists(array2, isFour)}");
Console.WriteLine("");
Console.WriteLine("Three dimensional case");
int[,,] array3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };
Console.WriteLine($"Is one existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array3)}: {MDArrayHelpers.Exists(array3, isFour)}");
Console.WriteLine("");
Console.WriteLine("Four dimensional case");
int[,,,] array4 = { { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } }, { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } } };
Console.WriteLine($"Is one existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isOne)}");
Console.WriteLine($"Is four existed in {nameof(array4)}: {MDArrayHelpers.Exists(array4, isFour)}");
The output of the test code above:
One dimensional case
Is one existed in array1: True
Is four existed in array1: False
Two dimensional case
Is one existed in array2: True
Is four existed in array2: False
Three dimensional case
Is one existed in array3: True
Is four existed in array3: False
Four dimensional case
Is one existed in array4: True
Is four existed in array4: False
If there is any possible improvement, please let me know.