Find index of a value in an array

0

I want to look up the index of an array by a value:

List<string> list = new List<string>() { "Leão", "Guepardo", "Elefante" };
String[] array = new String[3] { "Leão", "Guepardo", "Elefante" };

For example, I want to look up the index of the value "Elephant", how can I do this? Is there a method? Can linq be able to do this search and return me an index?

    
asked by anonymous 09.08.2018 / 17:14

3 answers

1

For the array has this:

Array.IndexOf(array, "Elefante")

To list is:

list.IndexOf("Elefante")

Example:

using System;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var list = new List<string>() { "Leão", "Guepardo", "Elefante" };
        var array = new string[3] { "Leão", "Guepardo", "Elefante" };
        WriteLine(list.IndexOf("Elefante"));
        WriteLine(Array.IndexOf(array, "Elefante"));
    }
}

See running on .NET Fiddle . And in Coding Ground . Also I placed GitHub for future reference .

    
09.08.2018 / 17:22
1

I think this might solve your problem:

int index = list.FindIndex(a => a == "Elefante");

Do a linear search to get the index.

    
09.08.2018 / 17:20
1

IndexOf

  

Search the specified object and return the zero-based index of the   first occurrence within the entire List

 list.IndexOf("Elefante")

Array.IndexOf

  

Search the specified object and return the index of the first   occurrence in a one-dimensional array.

Array.IndexOf(array, "Elefante")

7D% 22 "> Running on dot.net fiddle     

09.08.2018 / 17:22