Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last x records from a list with Lambda

Tags:

c#

lambda

c#-4.0

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

What I got so far

 List<string> query = otherlist.Distinct().Select(a => a).ToList();
like image 578
Ivo Avatar asked Jul 08 '10 09:07

Ivo


3 Answers

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();
like image 183
Jens Avatar answered Nov 12 '22 12:11

Jens


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];
        }
    }
like image 5
Marc Gravell Avatar answered Nov 12 '22 13:11

Marc Gravell


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.

like image 4
tzaman Avatar answered Nov 12 '22 13:11

tzaman