Linq:按计算结果筛选并重复使用此结果

本文关键字:结果 筛选 计算 Linq | 更新日期: 2023-09-27 18:31:12

>我有一个集合(在 DbSet 中),我想按其属性(距离)的计算结果对其进行排序,并将其(重用距离)转换为不同的模型。每个条目的计算应该只发生一次(由于它是一个 DbSet,它将在数据库本身中执行)。

class InputModel {
    Vector3 position;
}
class OutputModel {
    double distance;
}
var inputList = getInputList(); // returns IQueryable<InputModel>
var outputList = inputList
.Where( x => (){
    var dist = calculateDistance( x.position );
    // calculateDistance() boils down to a simple equation that could directly translated to an sql-query (when typed in statically by hand)
    return dist < maxDistance;
})
.Select( x => () {
    return new OutputModel {
        distance = ???; // get the calculated distance somehow
})
.ToList();

我想到了两种可能的解决方案:

  1. 将所有条目从数据库中取出到容器中,并计算距离并在 foreach 循环中过滤出的条目。
  2. 按距离筛选,并在变换到输出模型时重新计算距离。

是否可以一次性完成此操作(首选是数据库本身的计算)?

Linq:按计算结果筛选并重复使用此结果

你可以做inputlist.where(....)。select(x=>calculatedistance).select(dist=> new outputmodel)...从我的手机发表评论,因此无法输入完整的声明。但应该为你指出正确的方向。基本上。拳头做哪里,然后选择距离。然后选择输出模型

假设您的目标是同时使用您计算的与实体的距离和实体本身进行OutputModel投影,则只需在执行计算时将其实体作为匿名类型投影计算:

var outputList = inputList
    .Select( x => new 
        {
            dist = calculateDistance( x.position ),
            entity = x
        } )
    .Where( x => x.dist < maxDistance )
    .Select( x => new OutputModel 
        {
            distance = x.dist,
            // and you have access to source entity via `x.entity`
        } )
    .ToList();

您可以先进行选择,然后在比较中使用所选值。

请试一试

var outputList = InputList
                 .Select(
                     x => new 
                      {
                        dist = calculateDistance( x.position )
                      }     
                  )
                 .Where(x => x.dist < maxDistance)
                 .Select(y => () {
                 return new OutputModel {
                     distance = y.dist // get the calculated distance Here
                 });

LINQ 查询语法自然使用 let 子句支持这一点。

下面介绍了如何将其应用于你的方案:

var outputList = 
    (from x in inputList
     let distance = ... // distance calculation expression using x
     where distance < maxDistance
     select new OutputModel { distance }
    ).ToList();