I have collection of objects. I need to sort it by difficult condition, using many properties and calculations. My solution is to define in object special int
property, that returns value, that OrderBy
shoultd sort by. This solution is not good enough.
State
property, then i开发者_开发问答f State = 1
, by Value1
property, if State = 2
, by Value2
property and so on.
Advice, please, some solution.You can order a collection by multiple criteria by using OrderBy for the first criterium and chaining the other criteria after that using ThenBy.
Your first criterium is to simply order by the State property. Your second criterium depends on the State property; assuming that Value1, Value2 and so on have the same type, you can use a switch
statement to select the right value:
IEnumerable<MyClass> result = items
.OrderBy(item => item.State)
.ThenBy(item =>
{
switch (item.State)
{
case 1: return item.Value1;
case 2: return item.Value2;
}
throw new Exception();
});
Implement IComparer and using OrderBy of LINQ
you can use an IComparer class;
just put all the logic you've given above into its compare method.
精彩评论