Aaron Aaron - 1 month ago 10
ASP.NET (C#) Question

How can I order query by SelectListItem?

I have situation where I need to order query by names - like
1. Green
2. Blue
3. Grey
4. Yellow

If query doesn't contain some elements then order must be maintained. Example, query doesn't contain "Blue" then the list will look like
1. Green
2. Grey
3. Yellow

I have made Model:

namespace MotorzWeb.ViewModels.Manage
{
public class UserClassifiedsCategoriesViewModel
{
public Int64 Id { get; set; } //Row Number
public string UserId { get; set; }
public string Name { get; set; }
public Int64? TotalClassifiedsByCategory { get; set; }
}
}


In this model previously mentioned names are called Name.
To get data from database I use query like:

var totalClassified = db.UserClassifiedsCategories
.Where(c => c.UserId == userId)
.ProjectTo<UserClassifiedsCategoriesViewModel>(mapper.ConfigurationProvider)
.ToList();


I think I should make List, where I define correct ordring, like so:

public static IEnumerable<SelectListItem> OrderedCategoryNames( ResourceManager resourceManager)
{
return new List<SelectListItem>
{
new SelectListItem { Text = resourceManager.GetString("Green"), Value = "Green" },
new SelectListItem { Text = resourceManager.GetString("Blue"), Value = "Blue" },
new SelectListItem { Text = resourceManager.GetString("Grey"), Value = "Grey" },
new SelectListItem { Text = resourceManager.GetString("Yellow"), Value = "Yellow" }
};

}


And then, here is the part that I haven't figured out... How can I order totalClassified query by OrderedCaregoryName list? Can someone give advice or examples?
Thank You so much :)

Answer

You can create another list where you specify the names in an ordered manner and use IndexOf method in OrderBy method. The OrderBy method takes a key selector function and IndexOf method will return the position (index) of the item in the list.

var totalClassified = db.UserClassifiedsCategories
                        .Where(c => c.UserId == userId)
              .ProjectTo<UserClassifiedsCategoriesViewModel>(mapper.ConfigurationProvider)
              .ToList();

var orderList = new List<String>
{
    "Green",
    "Blue",
    "Yellow",
    "Gray"
};

var totalClassifiedOrdered = totalClassified.OrderBy(d => orderList.IndexOf(d.Name));

totalClassifiedOrdered will be a collection of UserClassifiedsCategoriesViewModel. If you want a list of SelectListItem, you can do call Select method on the result to get that.

var optionList = totalClassifiedOrdered
                   .Select(x=>new SelectListItem { Value=x.Name, Name =x.Name}).ToList();