Jamie
Jamie

Reputation: 1679

Linq statement distinct not working on dates

I've been looking all over stackoverflow.com and the Interwebz to find out how to use Linq with Distinct(), but I'm not having any luck with my situation.

What I'm trying to do is show a list of dates (Aug 2015, July 2015, etc) with each date showing just once.

What happens is that the months are duplicated because you can publish a new blog post more than once in a month. I thought using Distinct would help, but it seems like it's not doing anything. When I try adding GroupBy(), my OrderByDescending stops working, and I'm not seasoned enough to simply turn this into an IList, which I've seen in a couple other examples.

BlogRepeater.DataSource = _PostRepository.GetAll(ConfigurationManager.GetSiteID())
    .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1))
    .Distinct().OrderByDescending(x => x.DatePublished)
    .Select(x => x.DatePublished.Value.Date);

What is the best way to be doing this?

I've tried taking pieces from other examples, to no avail. Thanks in advance.

enter image description here

UPDATE: Thanks for the help! Here is working code in hopes it can help someone else in the future.

Code Behind:

BlogRepeater.DataSource = 
            _PostRepository
            .GetAll(ConfigurationManager.GetSiteID())
            .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1) && x.Status == "Published")
            .Select(x => x.DatePublished.Value.ToString("MMM yyyy"))
            .Distinct()
            .OrderBy(x => x);
        BlogRepeater.DataBind();

Front End:

<a href="/Blog/Archive/<%#(Container.DataItem)%>"><%#(Container.DataItem)%></a>

Upvotes: 1

Views: 587

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40516

If your DatePublished field contains DateTime values with different times, the .Distinct() will not behave how you expect it to, because those values are essentially different.

If you want distinct dates, not date/times, then you can move the last .Select before the .Distinct():

BlogRepeater.DataSource = 
  _PostRepository
    .GetAll(ConfigurationManager.GetSiteID())
    .Where(x => x.DatePublished != null && x.DatePublished >= DateTime.Now.AddYears(-1))
    .Select(x => x.DatePublished.Value.Date)   
    .Distinct()
    .OrderByDescending(x => x);

If you want to find the distinct months, not dates, then you have to change the

.Select(x => x.DatePublished.Value.Date)

line to

.Select(x => x.DatePublished.Value.ToString("MMM yyyy"))

Feel free to change the "MMM yyyy" format to anything else you find suitable.

Upvotes: 6

Related Questions