Reputation:
I am trying to find index of an array.
This is probably easy to do, but I havn't been able to find out how.
From a website, I tried to add a findIndex
function, but I am getting an error.
How can I find the index?
namespace exmple.Filters
{
class dnm2
{
public static byte[] Shape(byte[] data)
{
byte[] shape = new byte[data.Length];
byte count = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == 0)
{
shape[i] = (data[i]);
int index = shape.findIndex(count);
int[] a = {1, 2, 3};
int index = a.Indexof((int)3);
count += 1;
}
}
return shape;
}
public static int findIndex<T>(this T[] array, T item)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < array.Length; i++)
{
if (comparer.Equals(array[i], item))
{
return i;
}
}
return -1;
}
}
Upvotes: 2
Views: 6104
Reputation: 59615
Array.IndexOf() gives you the index of an object in an array. Just make sure you use the same data types, i.e. byte
here.
This is the full code, tested in .NET 4.5.2
using System;
namespace ConsoleApp2
{
class Program
{
static void Main()
{
byte[] data = { 5, 4, 3, 2, 1 };
Console.WriteLine(Array.IndexOf(data, (byte)2));
Console.ReadLine();
}
}
}
Upvotes: 3
Reputation: 1197
Not sure what you are trying to do but I have fixed your code.
namespace Exmple.Filters
{
public static class DNM
{
public static byte[] Shape(byte[] data)
{
byte[] shape = new byte[data.Length];
byte count = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == 0)
{
shape[i] = (data[i]);
int index = shape.FindIndex1(count);
int[] a = { 1, 2, 3 };
int index1 = Array.IndexOf(a, (int)3);
count += 1;
}
}
return shape;
}
public static int FindIndex1(this byte[] array, byte item)
{
EqualityComparer<byte> comparer = EqualityComparer<byte>.Default;
for (int i = 0; i < array.Length; i++)
{
if (comparer.Equals(array[i], item))
{
return i;
}
}
return -1;
}
}
}
there were few issues in your code
Upvotes: 0
Reputation: 16079
Alternate way is to use Array.FindIndex(array, predicate)
var zeroBasedIndex = Array.FindIndex(data, x => x == (byte)2);
Upvotes: 0