Search code examples
c#linq

LINQ - OrderByDescending


Please note: As of 1:47 PM UTC, Aug 26 2016, I completely modified this question because originally it was very confusing. My fault for that. So please ignore all answers/comments before this time. Thanks

I have a list of items that get added to a SearchItems list by SearchType... SearchType of ObjectAType, ObjectBType etc.. I want to OrderByDescending SearchTimes by items that have SearchType of ObjectAType or ObjectBType. For all other SearchType it needs to be order by ascending.

This is my query:

var orderdItems = SearchItems.OrderBy(i => i.ItemDisplay)
                             .OrderBy(i => i.CategoryDisplay))

This is the criteria I want to order by descending.

Where(x => x.SearchType == ObjectAType || x.SearchType == ObjectBType)

This is the structure of SearchItem

public class SearchItem
{
    public SearchItem() { }
    public Guid ItemId { get; set; }
    public string ItemDisplay { get; set; }
    public string CategoryDisplay { get; set; }
    public string SearchType { get; set; }
}

And this is how they get added to SearchItems = List<SearchItems>();

SearchItems.AddRange(items.Select(i => new SearchItem()
            {
                CategoryDisplay = "Object A",
                ItemDisplay = i.ObjectADisplay,
                ItemId = i.ObjectAId,
                SearchType = ObjectAType,
            }));

SearchItems.AddRange(items.Select(i => new SearchItem()
            {
                CategoryDisplay = "Object B",
                ItemDisplay = i.ObjectBDisplay,
                ItemId = i.ObjectBId,
                SearchType = ObjectBType,
            }));

and so on....'items' are IEnumerable<ObjectA>, IEnumerable<ObjectB> etc..


Solution

  • var desc = this.SearchItems
                   .Where(x => x.SearchType == Foo || x.SearchType == Bar)
                   .OrderByDescending(i => i.ItemDisplay)
                   .ThenByDescending(i => i.CategoryDisplay);
    var asc = this.SearchItems
                  .Where(x => x.SearchType != Foo && x.SearchType != Bar)
                  .OrderBy(i => i.ItemDisplay)
                  .ThenBy(i => i.CategoryDisplay);
    var result = desc.Concat(asc);
    

    Of course you can do it as one query as well.

    I assume that you want the 2 descending objects first. If that's not the case then turn the last statement around.

    var result = asc.Concat(desc);
    

    If you want to sort the list itself, then do this

    this.SearchItems = desc.Concat(asc).ToList();