以下关于排序的代码有什么问题?命中排序代码,但排序从不应用于结果。
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;
答案 0 :(得分:2)
OrderBy
和OrderByDescending
不会更改来电者,而是会返回新的IQueryable
/ IEnuemrable
。您必须将其分配回另一个(或相同的)变量。否则打电话给他们是没有意义的。
因为您正在使用List<T>
,所以您必须添加额外的ToList()
调用才能使其编译并正常工作:
if (orderBy == "Identifier")
{
if (direction == "ASC")
results = results.OrderBy(x => x.Identifier).ToList();
else
results = results.OrderByDescending(x => x.Identifier).ToList();
}
// (...)
或者您可以改为使用List<T>.Sort
:
if (orderBy == "Identifier")
{
if (direction == "ASC")
results.Sort((x1, x2) => x1.Compare(x2));
else
results.Sort((x1, x2) => x2.Compare(x1));
}