Alter
Alter

Reputation: 65

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

Upvotes: 2

Views: 283

Answers (2)

Reza Faghani
Reza Faghani

Reputation: 161

I am writing the probable solution in LINQ maybe and I hope it will be helpful. The error is due to the fact that indices in arrays start on zero it shows 3

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

   ocean.Select((x, i) => new { Value = x, Index = i }).ForEach(element =>
   {
       if (element.Value == "Nemo")
       {
           Console.WriteLine("We found Nemo on position {0}!",element.Index);
       }
   });

How to use it in compiler

Upvotes: 1

juharr
juharr

Reputation: 32296

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

Upvotes: 4

Related Questions