Linq表达式使用函数从Last中获取谓词项



是否存在从source list结尾给出谓词列表的Linq表达式

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

应该给"zxc"

您可以使用以下方法:

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

不是最有效的方式,但工作和可读性。

如果你真的需要它作为一个单一的(优化的)方法,你可以使用:

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];
    }
}

然后更简洁:

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

最新更新