Bryan
Bryan

Reputation: 3541

Order by date and convert to string In list

I have the following code:

List<EncryptionReport> result = null;
result = m_encryptionSvc.GetReportsFromRefnr(tuples);

result = result
  .OrderByDecending(e => e.Acc_date)
  .ThenBy(e => e.Acc_date.ToString("YYYY-mm-dd H:mm:ss"))
  .ToList();

The thing I want to Is sort by date in descending order and then parse the dates to string-format. But the parsing don't work.

How can I parse the dates to string after the sorting?

Solution

      var test = result.OrderBy(e => e.Acc_date)
                    .Select(x => 
                        new 
                        { 
                            x.Accident_nr,
                            x.Encrypted,
                            x.ExistsInStrada,
                            x.Id,
                            x.Original,
                            x.Report_id,
                            x.ReportSource,
                            x.State,
                            @Acc_date = x.Acc_date.ToString("yyyy-MM-dd hh:mm:ss")
                        })
                    .ToList();

Upvotes: 1

Views: 1916

Answers (2)

Allan Cadenilla
Allan Cadenilla

Reputation: 11

Assuming you want to get back a list of EncryptionReport after sorting. I would create another get only property in EncryptionReport object that returs a string of the date for you want.

public class EncryptionReport {

    //Other properties


    public string Acc_date_formatted { get { return Acc_date.ToString("YYYY-mm-dd H:mm:ss");} ]
}

List<EncryptionReport> result = null;
result = m_encryptionSvc.GetReportsFromRefnr(tuples);

result = result
  .OrderByDecending(e => e.Acc_date)
  .ToList();

Upvotes: 1

Steve
Steve

Reputation: 216273

If you just want a list of strings with your Acc_date value formatted according to your requirements, then you need to call Select after the OrderBy

List<string> dates = result.OrderByDescending(e => e.Acc_date)
                           .Select(x => x.Acc_date.ToString("YYYY-mm-dd H:mm:ss"))
                           .ToList();

Of course you cannot assign the return of this to the same result (a List) variable but you need a separate List<string>

Upvotes: 3

Related Questions