Rubix_Revenge Rubix_Revenge - 3 months ago 9
C# Question

Order column by a separate `List<string>` variable

I need to sort the results of an entity framework query by the index of elements in another list.

I tried the suggestion found elsewhere, like

.ThenBy(m=>list.IndexOf(m.Term))


but I get an HTTP 500 error, so I'm wondering if I'm missing something. When debugging, I get this inner exception.


LINQ to Entities does not recognize the method 'Int32
IndexOf(System.String)' method, and this method cannot be translated
into a store expression.


In particular, I'm thinking of this scenario.

private IEnumerable<MiaLog1A> PopulateQuery(string selectedCampus)
{
var list = new List<string> {"No Longer Alphabetical","Fall","Mid","Spring"};
return _db.MiaLog1A.Where(m => m.Campus == selectedCampus)
.OrderBy(m => m.StudentName)
.ThenBy(m=>m.Term)
/* I would like to sort "Term" by the
* order of "list".
*/
.AsEnumerable();
}


Is there a way I could sort in this manner, or am I restricted to ordering by a dictionary or creating a join?

Answer

this should do the trick:

private IEnumerable<MiaLog1A> PopulateQuery(string selectedCampus)
{
    var list = new List<string> {"Fall","Mid","Spring"};
    return _db.MiaLog1A.Where(m => m.Campus == selectedCampus)
        .AsEnumerable()
        .OrderBy(m => m.StudentName)
        .ThenBy(m=> list.IndexOf(m.Term));
}
Comments