2

I have a list of complex objects and would like to order it with linq (to objects) according to an "order-by-keyword":

protected override sealed List<IndexViewModel> Order(List<IndexViewModel> listToOrder, string orderBy)
{
    List<IndexViewModel> indexViewModels;
    switch (orderBy.ToLower())
    {
        case "creator":
            indexViewModels = listToOrder.OrderBy(s => s.Creator).ToList();
            break;
        case "startdate":
            indexViewModels = listToOrder.OrderBy(s => s.StartDate).ToList();
            break;
        ...
        default:
            indexViewModels = listToOrder.OrderBy(s => s.CreationDate).ToList();
            break;
    }

    return indexViewModels;
}

Is there any way to improve my code? Probably by assigning my keyword to linq and let it decide how to sort it?

mosquito87
  • 4,270
  • 11
  • 46
  • 77
  • from my point of view, i dont see any optimization, its a fairly simple problem with simple solution. – Parimal Raj Aug 12 '14 at 16:05
  • 1
    @SriramSakthivel was quick to close this question, but there is a simpler solution that is typesafe and doesn't require reflection. You can define a method like this: `private static Func GetOrder(string orderBy) { switch (orderBy.ToLower()) { case "creator": return s => s.Creator; case "startdate": return s => s.StartDate; default: return s => s.CreationDate; } }` This won't improve performance, but it is cleaner, and it will allow you to use it within a Linq query: `myItems.OrderBy(GetOrder("creator")).Select( ... ).FirstOrDefault()` – JLRishe Aug 12 '14 at 16:11
  • @JLRishe Your methos isn't prettier at all. How it is cleaner? You moved OP's switch statement to separate method and nothing else. Suggested duplicate can handle whatever the property is. No switch case needed. – Sriram Sakthivel Aug 12 '14 at 21:05
  • @SriramSakthivel I can understand that it's hard to see how my method is any prettier than the original when it's scrunched into a comment box (thank you for that), but the body of my method 9 lines instead of the 14 (15) the original has, and it eliminates all of the duplicate code. Where he has `indexViewModels = listToOrder.OrderBy(s => s.CreationDate).ToList(); break;`, I have `return s => s.CreationDate;`. That is much cleaner. And as I said, it has the huge advantage of being usable within a Linq statement instead of having to be used as a separate statement. – JLRishe Aug 13 '14 at 04:21
  • @SriramSakthivel Also as I already said, compared to your proposed duplicate, mine is typesafe. If someone refactored the `CreationDate` property to be named `CreatedDate`, it would break the approach you linked to, but not mine. The one you linked to is certainly a clever and useful one, and Marc Gravell is a more talented developer than I, but OP here was asking us to improve his code. – JLRishe Aug 13 '14 at 04:24

0 Answers0