如何使用Lambda从列表中获取最后的x条记录

Ivo*_*Ivo 8 c# lambda c#-4.0

我有删除每个重复项的字符串列表,现在我想过滤它以获得最后5条记录.我怎样才能做到这一点?

到目前为止我得到了什么

 List<string> query = otherlist.Distinct().Select(a => a).ToList();
Run Code Online (Sandbox Code Playgroud)

Jen*_*ens 10

你不需要.Select(a => a).多余的.

你可以通过跳过其余的来获得最后5条记录

List<string> query = otherlist.Distinct().ToList();
List<string> lastFive = query.Skip(query.Count-5).ToList();
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

编辑以满足非列表输入,现在处理IEnumerable<T>检查这是否是一个IList<T>; 如果不是通过对其进行缓冲ToList(),这有助于确保我们只能读取数据一次(而不是.Count().Skip()它可以读取数据多次).

由于这是一个列表,我倾向于编写一个扩展方法,使用它完整:

    public static IEnumerable<T> TakeLast<T>(
           this IEnumerable<T> source, int count)
    {
        IList<T> list = (source as IList<T>) ?? source.ToList();
        count = Math.Min(count, list.Count);
        for (int i = list.Count - count; i < list.Count; i++)
        {
            yield return list[i];
        }
    }
Run Code Online (Sandbox Code Playgroud)