如何在C#中找到数组的索引?

问题描述 投票:0回答:3

我正在尝试查找数组的索引。

这可能很容易做到,但我还没有找到方法。

从网站上,我尝试添加

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;
    }
}

c# arrays indexof
3个回答
2
投票

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();
        }
    }
}

0
投票

替代方法是使用 Array.FindIndex(array, predicate)

var zeroBasedIndex = Array.FindIndex(data, x => x == (byte)2);

0
投票

不确定你想做什么,但我已经修复了你的代码。

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;
        }
    }
}

您的代码中几乎没有问题

  1. 违反命名规则
  2. byte[] 已经有一个 FindIndex,所以编译器很困惑该使用哪一个(我刚刚删除了通用的东西并更改了名称)
  3. 数组对象没有 IndexOf 方法,数组类有方法。
© www.soinside.com 2019 - 2024. All rights reserved.