获取数组中特定项的索引

我想检索数组的索引,但是我只知道数组中实际值的一部分。

例如,我在数组中存储一个作者名,动态地输入“ author = ‘ xyz’”。
现在我想找到包含它的数组项的索引,因为我不知道值部分。

怎么做?

197074 次浏览

You can use FindIndex

 var index = Array.FindIndex(myArray, row => row.Author == "xyz");

Edit: I see you have an array of string, you can use any code to match, here an example with a simple contains:

 var index = Array.FindIndex(myArray, row => row.Contains("Author='xyz'"));

Maybe you need to match using a regular expression?

try Array.FindIndex(myArray, x => x.Contains("author"));

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());

The previous answers will only work if you know the exact value you are searching for - the question states that only a partial value is known.

Array.FindIndex(authors, author => author.Contains("xyz"));

This will return the index of the first item containing "xyz".

FindIndex Extension

static class ArrayExtensions
{
public static int FindIndex<T>(this T[] array, Predicate<T> match)
{
return Array.FindIndex(array, match);
}
}

Usage

int[] array = { 9,8,7,6,5 };


var index = array.FindIndex(i => i == 7);


Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.


Bonus: IndexOf Extension

I wrote this first not reading the question properly...

static class ArrayExtensions
{
public static int IndexOf<T>(this T[] array, T value)
{
return Array.IndexOf(array, value);
}
}

Usage

int[] array = { 9,8,7,6,5 };


var index = array.IndexOf(7);


Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.