Kowalski Kowalski - 2 months ago 9
C# Question

Linq Expression Get Predicated Items From Last With a Function

Are there any

Linq
expression exists that gives a predicated list form end of the
source list
.

i.e:
"abc1zxc".ToCharArray().SomeMagicLinq(p=>Char.IsLetter(p));


should give "zxc"

Answer

You could use this approach:

var lastLetters = "abc1zxc".Reverse().TakeWhile(Char.IsLetter).Reverse();
string lastLettersString = new String(lastLetters.ToArray());

Not the most efficient way but working and readable.

If you really need it as a single (optimized) method you could use this:

public static IEnumerable<TSource> GetLastPart<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
 {
    var buffer = source as IList<TSource> ?? source.ToList();
    var reverseList = new List<TSource>();
    for (int i = buffer.Count - 1; i >= 0; i--)
    {
        if (!predicate(buffer[i])) break;
        reverseList.Add(buffer[i]);
    }
    for (int i = reverseList.Count - 1; i >= 0; i--)
    {
        yield return reverseList[i];
    }
}

Then it's more concise:

string lastLetters = new String("abc1zxc".GetLastPart(Char.IsLetter).ToArray());