我有以下lambda表达式:
string queryToken = queryTokens.Last();
var result = from locationAddress in locations
let tokens = GetLetterTokens(locationAddress.Name)
let distance = (from token in tokens
where token.Contains(queryToken, StringComparison.OrdinalIgnoreCase)
select token.Length - queryToken.Length).Min()
orderby distance
select new
{
LocationAddress = locationAddress,
LocationDistance = distance,
};
它写的是什么并不重要。有时在计算distance
时,没有tokens
包含queryToken
,因此无法返回.Min()
。如何跳过这些案例?我不想将它们添加到result
变量中。
答案 0 :(得分:2)
听起来你只是想要:
let tokens = ...
where tokens.Any(token.Contains(queryToken, StringComparison.OrdinalIgnoreCase))
let distance = ...
或者,只需在选择令牌时进行过滤,然后检查是否存在:
var result = from locationAddress in locations
let tokens = GetLetterTokens(locationAddress.Name)
.Where(token => token.Contains(queryToken, StringComparison.OrdinalIgnoreCase)
where tokens.Any()
let distance = tokens.Min(token => token.Length - queryToken.Length)