当'let'无法在lambda表达式中计算时,跳过添加元素

时间:2012-08-28 14:44:43

标签: c# lambda

我有以下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变量中。

1 个答案:

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