简体   繁体   English

获取数组中特定项的索引

[英]Getting the index of a particular item in array

I want to retrieve the index of an array but I know only a part of the actual value in the array.我想检索数组的索引,但我只知道数组中实际值的一部分。

For example, I am storing an author name in the array dynamically say "author = 'xyz'".例如,我将作者姓名动态存储在数组中,例如“author = 'xyz'”。
Now I want to find the index of the array item containing it, since I don't know the value part.现在我想找到包含它的数组项的索引,因为我不知道值部分。

How to do this?这个怎么做?

You can useFindIndex您可以使用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 ?也许您需要使用正则表达式进行匹配?

尝试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".这将返回包含“xyz”的第一个项目的索引。

FindIndex Extension FindIndex 扩展

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奖励:IndexOf 扩展

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.这是一个小提琴。

string[] days = { "monday","tuesday","wednesday","thursday","friday","saturday" };
int index = Array.FindIndex(days, day => day.Equals("wednesday"));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM