如何捕获在where子句中创建的Linq(方法语法)值?

时间:2017-02-28 16:01:24

标签: c# linq variables

我确定已经回答了,我找不到它。无论如何,我有一个Linq声明,我根据用户输入将GeoCoorinate与另一个GeoCoordinate进行比较:

var agents = db.AllAgentLocations()
                    .AsEnumerable()
                    .Where(al => al.PrimaryOffice)
                    .Where(al => (25 >= (searchCoords.GetDistanceTo(
                                new GeoCoordinate
                                {
                                    Latitude = double.Parse(al.Location.Latitude),
                                    Longitude = double.Parse(al.Location.Longitude)
                                }
                        ) / 1609.34)))
                        .Select(a => a.Agent);

查询工作正常,我得到IEnumerable的预期输出。我试图找出一种输出

生成的距离的方法
(25 >= (searchCoords.GetDistanceTo(
      new GeoCoordinate
      {
          Latitude = double.Parse(al.Location.Latitude),
          Longitude = double.Parse(al.Location.Longitude)
      }
      ) / 1609.34)

我希望将代理和距离放入IEnumerable中,如下所示:

public class AgentDistanceViewModel
{
    public Agent Agent { get; set; }
    public double Distance { get; set; }
}

2 个答案:

答案 0 :(得分:3)

只需在Where子句之前添加一个投影(Select),将输入对象转换为新对象,然后就可以将Where子句应用于新对象:

function readFile(str,logFiles,callback){
    searchStr = str;
    for(var i=0; i<logFiles.length; i++){
        if(logFiles[i].filename !== '.gitignore'){
            fs.readFile('logs/dit/' + logFiles[i].filename, 'utf8', function (err,data) {
              if (err) {
                return console.log(err);
              }
              inspectFile(data,callback);
              callback(result);
              result = [];
            });
        }
    }

}

function inspectFile(data,callback) {
    var lines = data.split('\n');              // get the lines
    lines.forEach(function(line) {             // for each line in lines
        if(line.indexOf(searchStr) != -1) {    // if the line contain the searchSt
            result.push(line);
            // then log it
            return line;
        }
    });
    cb(callback);
}

function cb (callback) {
    callback(result);
}

将Linq查询视为&#34; SQL for C#&#34;更有帮助。但作为将变换应用于对象流的框架。您可以随时以任何顺序应用投影,过滤,排序等。如果最后的结果缺少某些信息,那么只需在某处添加一个转换即可添加它!

答案 1 :(得分:1)

您可以在过滤之前将值投影到目标类型

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
// Setting it to .NoCache always forces a new request
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.NoCache;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;

HttpClient client = new HttpClient(filter);
// .. your request code