Complex OrderBy: 语句体无法转换为表达式树
Complex OrderBy: Statement body cannot be converted to expression tree
基本上我试图从我的数据库中检索对象列表(使用 Entity Framework 6),但是我希望以某种方式对项目进行排序。
我试过以下方法:
context.Coordinates.OrderBy(x =>
{
double latDif = Math.Abs(centerLat - x.Longtitude);
double lngDif = Math.Abs(centerLng - x.Latitude);
double dif = latDif + lngDif;
return dif;
});
但是,编译器显示以下错误:
A lambda expression with a statement body cannot be converted to an
expression tree
我查了一下,了解到在 linq-to-sql.
中调用 orderby 时我不能使用语句体(大括号)
但是,如何在不加载所有条目的情况下像上面那样执行复杂的 orderby?
顺便说一下,如果您想知道我正在尝试按最接近中心坐标(centerLat 和 centerLng)的项目排序。
你可以做到这一点。
context.Coordinates.OrderBy(x=> Math.Abs(centerLat - x.Longtitude) + Math.Abs(centerLng - x.Latitude));
如果您希望根据多列进行排序,请使用
.OrderBy(x=> new {
// fields or props or columns
})
基本上我试图从我的数据库中检索对象列表(使用 Entity Framework 6),但是我希望以某种方式对项目进行排序。
我试过以下方法:
context.Coordinates.OrderBy(x =>
{
double latDif = Math.Abs(centerLat - x.Longtitude);
double lngDif = Math.Abs(centerLng - x.Latitude);
double dif = latDif + lngDif;
return dif;
});
但是,编译器显示以下错误:
A lambda expression with a statement body cannot be converted to an expression tree
我查了一下,了解到在 linq-to-sql.
中调用 orderby 时我不能使用语句体(大括号)但是,如何在不加载所有条目的情况下像上面那样执行复杂的 orderby?
顺便说一下,如果您想知道我正在尝试按最接近中心坐标(centerLat 和 centerLng)的项目排序。
你可以做到这一点。
context.Coordinates.OrderBy(x=> Math.Abs(centerLat - x.Longtitude) + Math.Abs(centerLng - x.Latitude));
如果您希望根据多列进行排序,请使用
.OrderBy(x=> new {
// fields or props or columns
})