开发者

How to get last x records from a list with Lambda

开发者 https://www.devze.com 2023-01-06 21:00 出处:网络
I have as List of strings with where i remove each duplicates, now I want to filter it even more to get开发者_Python百科 the last 5 records. How can I do this?

I have as List of strings with where i remove each duplicates, now I want to filter it even more to get开发者_Python百科 the last 5 records. How can I do this?

What I got so far

 List<string> query = otherlist.Distinct().Select(a => a).ToList();


You do not need the .Select(a => a). Thats redundant.

You can get the last 5 records, by skipping over the rest like

List<string> query = otherlist.Distinct().ToList();
List<string> lastFive = query.Skip(query.Count-5).ToList();


edit to cater for non-list inputs, now handles IEnumerable<T> and checks if this is an IList<T>; if not it buffers it via ToList(), which helps ensure we only read the data once (rather than .Count() and .Skip() which may read the data multiple times).

Since this is a list, I'd be inclined to write an extension method that uses that to the full:

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


How about this?

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

edit: here's the whole thing -

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

Also note that you shouldn't call it query if you've got a ToList() call at the end, because then it's not a query anymore, it's been evaluated and turned into a list. If you only need it to iterate over, you can omit the ToList() call and leave it as an IEnumerable.


var count=list.Count();
var last5=list.Skip(count-5);

EDIT:

I missed that the data is List<T> . This approach would be better for IEnumerable<T>

0

精彩评论

暂无评论...
验证码 换一张
取 消