Search code examples
c#arraysstringparsingint

Converting string to int from array


I am trying to print out the exact location of an array element but am coming out short

string[] ocean = { "Beebo", "Jeff","Arthur", "Nemo", "Dory" };

foreach(string fish in ocean)
{
    if (fish == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!",int.Parse(fish));
        return;
    }
}

Console.WriteLine("He was not here");

I need the {0} token to be replaced with the array index of that element in this case with 3 but i am failing at the int.Parse(fish) which obviously isn't working


Solution

  • The easiest way to get this working is by switching to a for loop

    for(int i = 0; i < ocean.Length; i++)
    {
        if (ocean[i] == "Nemo")
        {
            Console.WriteLine("We found Nemo on position {0}!", i);
            return;
        }
    }
    Console.WriteLine("He was not here");
    

    Alternatively you can keep track of the index in a foreach

    int index = 0;
    foreach(string fish in ocean)
    {
        if (fish == "Nemo")
        {
            Console.WriteLine("We found Nemo on position {0}!", index);
            return;
        }
    
        index++;
    }
    Console.WriteLine("He was not here");
    

    Or you can avoid the loop altogether and use Array.IndexOf. It will return -1 if the value is not found.

    int index = Array.IndexOf(ocean, "Nemo");
    if(index >= 0)
        Console.WriteLine("We found Nemo on position {0}!", index);
    else
        Console.WriteLine("He was not here");
    

    And here's a Linq solution

    var match = ocean.Select((x, i) => new { Value = x, Index = i })
        .FirstOrDefault(x => x.Value == "Nemo");
    if(match != null)
        Console.WriteLine("We found Nemo on position {0}!", match.Index);
    else
        Console.WriteLine("He was not here");