LINQ OrderBy和Where结合在一起

时间:2017-01-26 16:21:54

标签: c# linq linq-to-objects

在以下情况下,我试图避免多次检查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中可以避免这种情况吗?

1 个答案:

答案 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);