0

我试图找到存储在数组中的元素的索引,一些元素反复出现,当我试图获取这些元素的索引时,它总是给出第一个元素的索引。例如:

int[] arr = {3,5,6,7,2,3,11,14 };
        int index = Array.IndexOf(arr, 3);
        Console.WriteLine(index);
        Console.ReadLine();

当我想将 3 的索引设为 5 时,它仍然给出 0。我不能跳过我的逻辑中的元素,我必须每次在我的程序中检查每个元素。如果可以,请提供帮助。

问候。

4

6 回答 6

1

我假设您正在搜索与搜索项在数组中出现的次数无关的解决方案。在这种情况下,您需要一个循环,在其中对找到的当前项目执行工作

int[] arr = {3,5,6,7,2,3,11,14 };
int index = -1;
while((index = Array.IndexOf(arr, 3, index + 1)) != -1)
{
    Console.WriteLine(index);
}

Array.IndexOf (array, object, startindex)重载将完全按照您的预期工作

于 2013-05-07T10:55:52.077 回答
1

有一个IndexOf采用起始索引的数组的重载。使用第一项的索引来查找下一项:

int[] arr = {3,5,6,7,2,3,11,14 };

int index = Array.IndexOf(arr, 3);
Console.WriteLine(index);

int index2 = Array.IndexOf(arr, 3, index + 1);
Console.WriteLine(index2);

Console.ReadLine();
于 2013-05-07T10:53:33.973 回答
0

You can have a class that implements IEnumerable and returns the indices you want:

public class Traverse<T> : IEnumerable<int>
{
    T[] _list;
    T _value;

    public Traverse(T[] list, T value)
    {
        this._list = list;
        this._value = value; 
    }

    public IEnumerator<int> GetEnumerator()
    {
        for (int i = 0; i < _list.Length; i++)
            if (_list[i].Equals(_value))
                yield return i;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

And use it like this:

    int[] arr = { 3, 5, 6, 7, 2, 3, 11, 14 };

    foreach (var index in new Traverse<int>(arr, 3))
        Console.WriteLine(index.ToString());

output: 0 5

于 2013-05-07T11:26:31.810 回答
0

试试下面:

int[] arrRepaetInd = new int[arr.Length];
int j=0,cnt=0;
for(int i=0;i<arr.Length;i++)
{
  j++;
  if(arr[i]==arr[i+1]
  {
    cnt++;
    arrRepaetInd[cnt]=arr[i];
    Console.WriteLine(arrRepaetInd[cnt]);
  }
}

arrRepaetInd 数组具有重复元素的索引。

于 2013-05-07T10:55:58.030 回答
0

您想使用 Select 加上一个过滤器。

public int[] IndexesOf<T>(T[] Values, T find) {
    return Values.Select((i,index) => new { index = index, value = i})
                 .Where(x => x.value == find)
                 .Select(x => x.index)
                 .ToArray();
}

甚至作为扩展方法

public static class MyExtensions {
    public static int[] IndexesOf<T>(this T[] Values, T find) {
        return Values.Select((i,index) => new { index = index, value = i})
                     .Where(x => x.value == find)
                     .Select(x => x.index)
                     .ToArray();
    }
}

然后你可以做

var indexes = arr.IndexesOf(3);
于 2013-05-07T10:56:49.297 回答
0

您可以使用LINQ-Select(IEnumerable<TSource>, Func<TSource, Int32, TResult>)这里是MSDN Link

var indexes = arr.Select((i, index) => new { Number = i, Index = index }).Where(x => x.Number == 3).Select(x => x.Index).ToArray();

然后获取最后一个索引(如果这是你想要的)使用LastOrDefault(), 作为ToArrray.

于 2013-05-07T10:52:17.987 回答