Search code examples
c#.netarraysindexingcontain

Find last index of string in string array containing a value



In my program I have a text, which I'm splitting up into an Array of lines to modify the lines separately. For one modification I need to find the last index of a value in the text, to insert a new value in the line below.

Example:

text=["I like bananas",
      "I like apples",
      "I like cherries",
      "I like bananas",
      "I like apples"]

value: "bananas"

I already tried to use:

int pos = Array.FindIndex(text, row => row.Contains(value));
if (pos > -1)
{
 //insert line at pos
}

but this seems to return me the index of the first occurence. "lastIndexOf()" seems neither to be the right command for me as this looks for equality of the given value and the items in the array.

Am I doing something wrong or is there another command, to use in this case?


Solution

  • I don't get what is wrong with Array.FindLastIndex() method. It works exactly in the same way:

    string value = "bananas";
    string[] arr = 
    {
        "I like bananas", 
        "I like apples",
        "I like cherries",
        "I like bananas",
        "I like apples"
    };
    
    Console.WriteLine(Array.FindLastIndex(arr, x => x.Contains(value)));
    

    This code works for me and outputs "3".