我正在尝试查找数组的索引。
这可能很容易做到,但我还没有找到方法。
从网站上,我尝试添加
findIndex
功能,但出现错误。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;
}
}
Array.IndexOf() 为您提供数组中对象的索引。只需确保您使用相同的数据类型,即此处的
byte
。
这是完整的代码,在 .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();
}
}
}
替代方法是使用 Array.FindIndex(array, predicate)
var zeroBasedIndex = Array.FindIndex(data, x => x == (byte)2);
不确定你想做什么,但我已经修复了你的代码。
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;
}
}
}
您的代码中几乎没有问题