如何获取数组中重复元素的索引..?

时间:2013-05-07 10:49:54

标签: c# asp.net

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

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

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

问候。

6 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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)重载将完全按预期工作

答案 2 :(得分:0)

您可以使用LINQSelect(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的使徒。

答案 3 :(得分: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数组包含重复元素的索引。

答案 4 :(得分: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);

答案 5 :(得分:0)

您可以拥有一个实现IEnumerable的类并返回您想要的索引:

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

并像这样使用它:

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

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

输出: 0 5

相关问题