Kowalski Kowalski - 1 year ago 89
C# Question

Linq Expression Get Predicated Items From Last With a Function

Are there any

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


should give "zxc"

Answer Source

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;
    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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download