LINQ is a great tool but wrong for this kind if problem. LINQ acts upon IEnumerable<T>
s the same things that you can use a foreach
on and one thing you cannot do when you enumerate a collection with foreach
is modifying that collection by removing items. Think of LINQ as pure functions, they never really modify stuff. They read from one enumerable and returns new things. It's all built on the Iterator pattern and very cool and smart stuff.
So the answer is you should not convert it to a LINQ expression. But I did anyway:
var returnString = new string (s.Reverse().SkipWhile(
c =>
{
var skipped = false;
if (c == '&' && !skipped)
{
skipped = true;
return true;
}
else
{
return false;
}
}).Reverse().ToArray());
But don't use this, according to my primitive test this is about 3000 times slower then using TrimEnd