106

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'".
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?

3
  • are you using Array or string []? Commented Dec 8, 2010 at 14:36
  • its a string[] and i want to find something Array.Indexof(arrFilter, "author") here author is not the complete value rather a part of the complete value Commented Dec 8, 2010 at 14:38
  • 1
    possible duplicate of Find index of a value in an array Commented Feb 10, 2014 at 9:30

6 Answers 6

185

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?

Sign up to request clarification or add additional context in comments.

1 Comment

One could also make this an array extensions for easier use and IntelliSense.
16

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

Comments

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

Comments

10

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".

Comments

8

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.

Comments

2

You can use Array.IndexOf() method.

var index = Array.IndexOf(myArray,valueToFind);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.