在以下情况下,我试图避免多次检查DistanceTo
方法:
public IEnumerable<Object> NearbyObjects => Objects.Where(o => a.DistanceTo(o) < 10).OrderBy(o => a.DistanceTo(o));
或
public IEnumerable<Object> NearbyObjects => Objects.OrderBy(o => a.DistanceTo(o)).TakeWhile(o => a.DistanceTo(o) < 10);
无论如何,我必须使用DistanceTo
方法两次。在LINQ中可以避免这种情况吗?
答案 0 :(得分:3)
您可以在linq查询语法中使用let
语句,如下所示:
public IEnumerable<Object> NearbyObjects =>
from o in Objects
let distanceTo = a.DistanceTo(o)
where distanceTo < 10
orderby distanceTo
select o;
如果要使用方法语法,则必须临时投影到匿名类型
public IEnumerable<Object> NearbyObjects =>
Objects.Select(o => new { o, distanceTo = a.DistanceTo(o) })
.Where(o => o.distanceTo < 10)
.OrderBy(o => o.distanceTo)
.Select(o => o.o);