Reputation: 1
I have the following table.
Name Date
A 10/04/2016
A 10/03/2016
A 10/05/2016
B 10/02/2016
B 10/01/2016
B 10/03/2016
C 10/05/2016
C 10/02/2016
C 10/04/2016
I would like to display this
Name Date
B 10/01/2016
B 10/02/2016
B 10/03/2016
C 10/02/2016
C 10/04/2016
C 10/05/2016
A 10/03/2016
A 10/04/2016
A 10/05/2016
How to create a query to get this result.
Upvotes: 0
Views: 2196
Reputation: 6090
var elements = new[]
{
new { Name = "A", Date = DateTime.Parse("10/04/2016") },
new { Name = "A", Date = DateTime.Parse("10/03/2016") },
new { Name = "A", Date = DateTime.Parse("10/05/2016") },
new { Name = "B", Date = DateTime.Parse("10/02/2016") },
new { Name = "B", Date = DateTime.Parse("10/01/2016") },
new { Name = "B", Date = DateTime.Parse("10/03/2016") },
new { Name = "C", Date = DateTime.Parse("10/05/2016") },
new { Name = "C", Date = DateTime.Parse("10/02/2016") },
new { Name = "C", Date = DateTime.Parse("10/04/2016") },
};
// LINQ to Objects
elements
.GroupBy(e => e.Name) // grouping by name
.Select(group => group.OrderBy(e => e.Date)) // order elements by date
.OrderBy(group => group.First().Date) // order groups by date
.SelectMany(group => group); // compose groups
// LINQ to Entities
elements
.GroupBy(e => e.Name)
.Select(group => group.OrderBy(e => e.Date))
.OrderBy(group => group.FirstOrDefault().Date)
.AsEnumerable()
.SelectMany(group => group);
Upvotes: 1
Reputation: 11
https://dotnetfiddle.net/0SfhAz
This is the fiddle with the code. For some reason, I can't get the fiddle to write out the values in the list.
I originally did this in LinqPad, and here is the output I got from the code in the fiddle when in LinqPad
I don't know why I can't just do a writeline on the .net fiddle, but it is being difficult. In case the fiddle doesn't work for you, here it the linq query I used for this
var orderedList = originalList.OrderBy(x => x.SomeDate).GroupBy(y => y.Name);
There may be better approaches, but this looked to solve your issue
Upvotes: 0
Reputation: 581
It would be great if you provide more information. Such as, the object type containing the data. Is it a custom model or a DataTable? Any how, I will try both.
var result = dataTable.Rows.AsEnumerable().GroupBy(x => x.Name).OrderBy(x => x.Date);
OR
var result = Foo.GroupBy(x => x.Name).OrderBy(x => x.Date);
Upvotes: 0
Reputation: 557
You probably do not need groupby but only orderby can fullfil your task:
yourList.OrderBy(l => l.Date).ThenBy(l => l.Name)
Upvotes: 0