1

I have gallery in my project and I want to group it by their upload date for example if page = 1 it should show 2019/1/2 pictures and if page = 2 it should show 2019/1/4 pictures but I can't do it. It says I can't select Dates[Page - 1].

public IEnumerable<GalleryPictures> GetGalleryByDates(int Page)
{
    var AllGalleryPictures = GetAllGalleryPictures();
    var Dates = AllGalleryPictures.Select(p => p.UploadDate).ToList().Distinct().OrderByDescending(p=>p);
    return AllGalleryPictures.Where(p => p.UploadDate == Dates[Page - 1]);

}
Emad
  • 3,809
  • 3
  • 32
  • 44
  • 2
    Add `ToList` after `Select` – Nkosi Jan 05 '20 at 14:45
  • Since you only need one date you can do `var date = AllGalleryPictures.Select(p => p.UploadDate).Distinct().OrderByDescending(p=>p).Skip(Page - 1).FirstOrDefault();` and use that. Note that this gives the default value when there are fewer than `Page` items, whereas what you're doing would result in an index out of range exception with the `ToList` moved to the end. – juharr Jan 05 '20 at 15:19

2 Answers2

1

This will fix your issue:

var Dates = AllGalleryPictures.Select(p => p.UploadDate).Distinct().OrderByDescending(p=>p).ToList();

Also read more about IEnumerable and LINQ

Emad
  • 3,809
  • 3
  • 32
  • 44
0

The accepted answer uses ToList, which materialises the query - that is, it allocates a List and executes the query expression for each possible element in the sequence.

In your case this is unlikely to cause a significant performance penalty, but if you are writing large and complex queries you may impact performance by making the application do lots of work to create result objects that will never be used.

To mitigate this, you can use ElementAt to access only the element you actually want. However do note that you have already made this irrelevant in your code example by calling ToList on the preceding line.

Tom W
  • 5,108
  • 4
  • 30
  • 52