Reputation: 751
I have a dynamic list that is populated and sorted:
List<dynamic> eventList = new List<object>();
foreach (Task t in tasks)
{
eventList.Add(
new
{
id = "t" + t.TaskID.ToString(),
title = t.TaskTitle,
start = ResolveStartDate(StartDate(t.Schedule.DateFrom.Value)),
end = ResolveEndDate(StartDate(t.Schedule.DateFrom.Value), t.Schedule.Hours.Value),
description = t.TaskDescription,
allDay = false,
resource = t.Schedule.EmployeID.ToString(),
color = ColorConversion.HexConverter(System.Drawing.Color.FromArgb(t.Project.Color.Value))
}
);
}
foreach (Case c in cases)
{
eventList.Add(
new
{
id = "c" + c.CaseID.ToString(),
title = c.CaseTitle + "-" + c.Customer.CustomerDescription,
start = ResolveStartDate(StartDate(c.Schedule.DateFrom.Value)),
end = ResolveEndDate(StartDate(c.Schedule.DateFrom.Value), c.Schedule.Hours.Value),
description = c.CaseDescription,
allDay = false,
resource = c.Schedule.EmployeID.ToString(),
color = ColorConversion.HexConverter(System.Drawing.Color.FromArgb(c.Color.Value))
}
);
}
eventList.OrderBy(p => p.title);
When I check in debug mode before and after the sort call, the list is not sorted at all, it is in the order added.
When I run it I see nothing is sorted either. What could be wrong?
Upvotes: 0
Views: 127
Reputation: 25434
The line below is just a query:
eventList.OrderBy(p => p.title);
It means, that it is something like class, struct statement. It only declarates some structure and do nothing more. In order to instatiate that query, you must copy it to an array or list as follows:
var sortedArray = eventList.OrderBy(p => p.title).ToArray();
After that, eventList will be iterated through and elements will be written to an array and stored in sortedArray variable.
Upvotes: 0
Reputation: 1502106
This is the problem:
eventList.OrderBy(p => p.title);
You're assuming that OrderBy
sorts the existing collection. It doesn't. It returns a sequence which is ordered. You're ignoring that return value, so the statement is useless.
You probably want:
eventList = eventList.OrderBy(p => p.title).ToList();
It's not just OrderBy
which works like this - all LINQ sequence operations (Select
, Where
, Join
etc) leave the original collection unchanged, and return a sequence with the appropriately projected, filtered (etc) data.
Upvotes: 2
Reputation: 8319
OrderBy
doesn't change the original list. It just creates a new one, with the same elements as the first one, but in a different order.
Try
eventList = eventList.OrderBy(p => p.title).ToList();
Upvotes: 1