Search code examples
c#arraysline-numbers

String array: search for text, return line number of first occurrence


In my string array, I want to look up some text and return the the line number of the first occurrence as an int.

This is working;

public static int LookUpLineNumber(String[] item, string TextToLookUp)
{
    int m;
    for (m = 0; m < item.Count(); m++)
    {
        if (item[m].Contains(TextToLookUp))
        {
            break;
        }
    }
    return m++;
}

However, I am wondering if there is any way to optimize it for efficiency and length?

Speed comparison: (average time on 10.000 runs with an string array of size 10.000)

  1. Using my code:

    • 1,259ms
  2. Using Habib's code: Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));

    • 0,906ms

Solution

  • Your current solution looks OK. You can have return m; instead of return m++.

    If you want to shorten your code you can use Array.FindIndex<T> like:

    public static int LookUpLineNumber(String[] item, string TextToLookUp)
    {
        return Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
    }
    

    Not really sure if it would give you any performance gain.