代码之家  ›  专栏  ›  技术社区  ›  Ivo

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

  •  8
  • Ivo  · 技术社区  · 14 年前

    我有一个字符串列表,其中我删除了每个重复,现在我想过滤它,甚至得到最后5条记录。我该怎么做?

    到目前为止我得到了什么

     List<string> query = otherlist.Distinct().Select(a => a).ToList();
    
    4 回复  |  直到 8 年前
        1
  •  10
  •   Jens    14 年前

    你不需要 .Select(a => a)

    你可以跳过剩下的5条记录,比如

    List<string> query = otherlist.Distinct().ToList();
    List<string> lastFive = query.Skip(query.Count-5).ToList();
    
        2
  •  5
  •   Marc Gravell    14 年前

    编辑 为了迎合非列表输入,现在处理 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];
            }
        }
    
        3
  •  4
  •   tzaman    14 年前

    这个怎么样?

    var lastFive = list.Reverse().Take(5).Reverse();
    

    编辑:事情是这样的-

    var lastFiveDistinct = otherlist.Distinct()
                                    .Reverse()
                                    .Take(5)
                                    .Reverse()
                                    .ToList();
    

    还要注意的是,你不应该称之为 query ToList() 在最后打电话,因为那时候 ToList() 打电话把它当作一个 IEnumerable .

        4
  •  0
  •   spender    14 年前
    var count=list.Count();
    var last5=list.Skip(count-5);
    

    编辑: