2012-08-28 38 views
1

內進行計數,我有以下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變量中。

回答

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) 
+0

感謝隊友:)完美的作品! – Nickon