Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

c# - LINQ orderby on date field in descending order

How can I change the LINQ query in the code below to sort by date in descending order (latest first, earliest last)?

using System;
using System.Linq;
using System.Collections.Generic;


namespace Helloworld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<Envelops> env = new List<Envelops> ();
            Envelops e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now.AddDays (5) };
            env.Add (e);
            e = new Envelops { ReportDate = new DateTime (2011, 3, 3) };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);

            foreach (Envelops r in env) {
                Console.WriteLine (  r.ReportDate.ToString("yyyy-MMM"));
            }

            var ud = (from d in env                  
                select  d.ReportDate.ToString("yyyy-MMM") ).Distinct();     

            Console.WriteLine ("After distinct");

            foreach (var r in ud) {
                Console.WriteLine (r);
            }

        }
    }

    class Envelops
    {
        public DateTime ReportDate { get; set; }
    }

}`enter code here`

the current output is:

2011-Apr
2011-May
2011-Mar
2011-Apr
After distinct
2011-Apr
2011-May
2011-Mar

I want the output to in the following order:

may
april
march order
question from:https://stackoverflow.com/questions/5813464/linq-orderby-on-date-field-in-descending-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't believe that Distinct() is guaranteed to maintain the order of the set.

Try pulling out an anonymous type first and distinct/sort on that before you convert to string:

var ud = env.Select(d => new 
                         {
                             d.ReportDate.Year,
                             d.ReportDate.Month,
                             FormattedDate = d.ReportDate.ToString("yyyy-MMM")
                         })
            .Distinct()
            .OrderByDescending(d => d.Year)
            .ThenByDescending(d => d.Month)
            .Select(d => d.FormattedDate);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...