Linq to Objects (When orderby does not order by but OrderBy does)
I must admit that while I have really enjoyed getting to know linq, it is not without it's frustrations. Sometimes things that seem like they should work, compile giving you that warm fuzzy, then in execute mode they turn out not to work. I understand that what this really means is that I don't yet intuitively grasp the internals of what is happening in the plumbing but perhaps one day I will.
With that being said, today's example is about my first use of orderby for a linq to object query. Consider this linq statement:
var needed = from a in myFCs
where a.Status == Status.Needed
orderby a.Priority, a.WeeksIncluded, a.QtyPlan
select a;
Looks ok, compiles ok, runs ok with the small issue that as you step through the collection the objects are not ordered as requested. My first thought was that I might need to modify my object class maybe add an additional interface or two. However a few minutes with google got me to here. Once I have created my needed collection I can then run another series of expressions against it like so:
var needed =(from a in myFCs
where a.Status == Status.Needed
select a).OrderBy(a => a.Priority)
.ThenBy(a => a.WeeksIncluded)
.ThenByDescending(a => a.QtyPlan);
Notice the nifty use of ThenByDescending for a nice direction change.
Comments