1

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

4

1 回答 1

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)
于 2012-08-28T14:48:56.527 回答