查找数组中某个值的所有索引号

本文关键字:索引 数组 查找 | 更新日期: 2023-09-27 18:22:04

如何在数组中查找值的所有位置

   class Program
    {
        static void Main(string[] args)
        {
            int start = 0;
           int[] numbers = new int[7] { 2,1,2,1,5,6,5};
    }

查找数组中某个值的所有索引号

类似的东西:

  int[] numbers = new [] { 2, 1, 2, 1, 5, 6, 5 };
  int toFind = 5;
  // all indexes of "5" {4, 6}
  int[] indexes = numbers
    .Select((v, i) => new {
      value = v,
      index = i
    })
    .Where(pair => pair.value == toFind)
    .Select(pair => pair.index)
    .ToArray();
List<int> indexes = new List<int>();
for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] == yourNumber)
        indexes.Add(i);
}

用途为:Array.indexOf(T,value)

请参阅下面的msdn。

http://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx

您可以为序列制作一个非常简单的扩展方法:

public static class SequenceExt
{
    public static IEnumerable<int> IndicesOfAllElementsEqualTo<T>
    (
        this IEnumerable<T> sequence, 
        T target
    )   where T: IEquatable<T>
    {
        int index = 0;
        foreach (var item in sequence)
        {
            if (item.Equals(target))
                yield return index;
            ++index;
        }
    }
}

扩展方法适用于List<>、数组、IEnumerable<T>和其他集合。

然后你的代码看起来像这样:

var numbers = new [] { 2, 1, 2, 1, 5, 6, 5 };
var indices = numbers.IndicesOfAllElementsEqualTo(5); // Use extension method.
// Make indices into an array if you want, like so
// (not really necessary for this sample code):
var indexArray = indices.ToArray();
// This prints "4, 6":
Console.WriteLine(string.Join(", ", indexArray));

Linq可以帮助

var indexes = numbers
  .Select((x, idx) => new { x, idx })
  .Where(c => c.x == number)
  .Select(c => c.idx);