Pergunta

What is wrong with the code below with regards to sorting? The sort code is hit, but the sorting is never applied to the results.

var results = new List<Location>();

var county = context.boc_County.Where(x => x.Description.Contains(phrase.ToLower())).ToList();
results.AddRange(_mapper.MapCountyFromDb(county));

var town = context.boc_Town.Where(x => x.Description.Contains(phrase.ToLower())).ToList();
results.AddRange(_mapper.MapTownFromDb(town));

if (orderBy == "Identifier")
{
    if (direction == "ASC")
        results = results.OrderBy(x => x.Identifier);
    else
        results = results.OrderByDescending(x => x.Identifier);
}

if (orderBy == "Type")
{
    if (direction == "ASC")
        results = results.OrderBy(x => x.LocationType.ToString());
    else
        results = results.OrderByDescending(x => x.LocationType.ToString());
}

if (orderBy == "Description")
{
    if (direction == "ASC") 
        results = results.OrderBy(x => x.Description);
    else
        results = results.OrderByDescending(x => x.Description);
}

var model = new LocationSearchResult()
{
    Locations = query.Skip(page * pageSize).Take(pageSize),
    TotalCount = query.Count()
};
return model;
Foi útil?

Solução

OrderBy and OrderByDescending don't change the caller, they return new IQueryable/IEnuemrable instead. You have to assign it back to another (or the same) variable. Otherwise calling them has no sense.

Because you're using List<T> you have to add additional ToList() call to make it compile and work:

if (orderBy == "Identifier")
{
    if (direction == "ASC")
        results = results.OrderBy(x => x.Identifier).ToList();
    else
        results = results.OrderByDescending(x => x.Identifier).ToList();
}
// (...)

or you can use List<T>.Sort instead:

if (orderBy == "Identifier")
{
    if (direction == "ASC")
        results.Sort((x1, x2) => x1.Compare(x2));
    else
        results.Sort((x1, x2) => x2.Compare(x1));
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top