Find an index of a value in a matrix

Asked

Viewed 77 times

1

I’m looking for a matrix index for 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 search the value index "Elephant", how can I do that? Do you have any method? , the linq is able to do this search and return me an index?

3 answers

2

Index

Searches the specified object and returns the zero-based index of first occurrence within the entire List

 list.IndexOf("Elefante")

Array.Indexof

Searches the specified object and returns the index of the first occurrence in a one-dimensional matrix.

Array.IndexOf(array, "Elefante")

Running on dot.net fiddle

1

I think this might solve your problem:

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

Do a linear search to get the index.

1


To the array has it:

Array.IndexOf(array, "Elefante")

For 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"));
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.