Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select then OrderBy using LINQ?

I am trying to sort the contents of a CSV file according to their dates with the following code from a question a posted earlier:

private class CSVEntry
{
    public DateTime Date { get; set; }
    public string Grp { get; set; }
}

...

List<CSVEntry> csvList = new List<CSVEntry>();

csvList.Add(new CSVEntry() { Date = DateTime.ParseExact(col[7], "dd/MM/yyyy", null), Grp = col[9] });

var results = csvList.OrderBy(x => x.Date); // An error occurs at "Date".

...

But I got this error:

'string' does not contain a definition for 'Date' and no extension method 'Date' accepting a first argument of type 'string' could be found.

What I want the output to be is the strings from other columns but sorted chronologically. When I tried using this code to display the dates:

var results = csvList.Where(x => x.Grp == "DEFAULT").OrderBy(x => x.Date);

It works perfectly with the output as dates sorted chronologically. However, this time I don't want to display the dates. I want to display the strings from other columns like I've mentioned above. I tried using

var results = csvList.Select(x => x.Grp).OrderBy(x => x.Date);

but got the same error as well. Where have I gone wrong? I am new to LINQ and unfamiliar with List<T> and IEnumerable<T> and this is my first time using them.

like image 607
user6234613 Avatar asked May 13 '16 09:05

user6234613


2 Answers

Add Select after your order the records, Like below

var results = csvList
    .Where(x => x.Grp == "DEFAULT")
    .OrderBy(x => x.Date)
    .Select(x => x.Grp);
like image 76
Rajshekar Reddy Avatar answered Sep 30 '22 04:09

Rajshekar Reddy


Reddy's answer should work, but I will explain it for you, so you understand why it does.

When you use the Select(x => x.Grp) Statement you don't have a IEnumerable<CSVEntry> anymore. You only have a IEnumerable with all Grp-Entrys from your csvList. So When you try to order them by Date by adding a OrderBy(x => x.Date) Statement, Linq doesn't know the Date Property, because in this Statement x is only a string, not a CsvEntry.

In Reddys Answer, he first filter all Entrys by Grp == "DEFAULT". After that he has a IEnumerable<CsvEntry> left, so he can Order them by x.Date. After that, again, he has a IEnumerable<CsvEntry> left. Only after the last Statement, the Select(x => x.Grp) Statement, he has a IEnumerable<string> left.

Hope that helps :)

like image 20
halliba Avatar answered Sep 30 '22 06:09

halliba