Snorlax Snorlax - 1 month ago 7
C# Question

Remove last occurrence of string in list

Is it possible to remove the last occurrence of a string from a list using Linq? Something like this:

var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad
arr.RemoveLast(x => x.Contains("hello")); //hello mom dad

Basically remove the last occurrence of the list. I need to use Contains on the string and it has to be a list.

list.RemoveAt(list.FindLastIndex(x => x.Contains("hello")));

This above will remove last string that contains "hello" in it. If there's a possibility that none of the string items satisfies the search condition, and the code in that case should do nothing, then it's like this:

int index = list.FindLastIndex(x => x.Contains("hello"));
if (index != -1)