获取数组中特定项的索引

Mac*_*Mac 66 c# arrays

我想检索一个数组的索引,但我只知道数组中实际值的一部分,例如我在数组中动态地存储作者名称说"author ='xyz'"我想找到数组项的索引包含类似作者的东西,因为我不知道价值部分如何做到这一点.

GvS*_*GvS 122

您可以使用FindIndex

 var index = Array.FindIndex(myArray, row => row.Author == "xyz");
Run Code Online (Sandbox Code Playgroud)

编辑:我看到你有一个字符串数组,你可以使用任何代码来匹配,这里有一个简单的例子包含:

 var index = Array.FindIndex(myArray, row => row.Contains("Author='xyz'"));
Run Code Online (Sandbox Code Playgroud)

也许你需要使用正则表达式进行匹配?


rpf*_*aco 11

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

  • 看来你错过了正确的括号. (4认同)

Tal*_*ner 9

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());
Run Code Online (Sandbox Code Playgroud)


Tab*_*ool 7

只有当您知道要搜索的确切值时,之前的答案才有效 - 问题表明只知道部分值.

Array.FindIndex(authors, author => author.Contains("xyz"));
Run Code Online (Sandbox Code Playgroud)

这将返回包含"xyz"的第一个项目的索引.


Mik*_*der 7

查找索引扩展

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

用法

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

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

Console.WriteLine(index); // Prints "2"
Run Code Online (Sandbox Code Playgroud)

这是一个摆弄它。


奖励:扩展索引

我首先写的没有正确阅读问题......

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

用法

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

var index = array.IndexOf(7);

Console.WriteLine(index); // Prints "2"
Run Code Online (Sandbox Code Playgroud)

这是一个摆弄它。