2

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

3
  • You could use Array.IndexOf to get the index of the fish name. Otherwise either use a for loop where you control the index or add a variable that you increment in the foreach to keep track of the index. Commented Jan 26, 2020 at 14:12
  • I haven't thought of multiple occurences, i only need the one occurence printed Commented Jan 26, 2020 at 14:17
  • All positions: string searchString = "Nemo"; int[] position = Enumerable.Range(0, ocean.Length).Where(idx => ocean[idx].Equals(searchString)).ToArray(); Commented Jan 26, 2020 at 14:38

2 Answers 2

4

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");    
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much but this was already known to me. I had my heart on a foreach this time
@Ale I've added a foreach solution and one that uses Array.IndexOf. I also tend to prefer foreach loops, but when I also need the index I almost always end up going back to the for loop instead.
1

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

10 Comments

A better Linq solution would be to use Where(x => x.Value == "Nemo").FirstOrDefault() and then you don't need to create a needless list with ToList just to use ForEach
good alternative, but it iterates twices through all elements, that's why it's not so efficient. And you can remove the ToList(), this isn't good for anything here.
@Holger The ToList is required to do the ForEach, but IMHO that's a horrible practice.
@juharr. Right, and your ideas misses the index. So if one wants to use LINQ, the answer is correct. Just to choose LINQ is not effective here.
Another issue with this solution is that it doesn't handle the case when no match is found.
|

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.