簡體   English   中英

C#:如果條件在Linq where子句中

[英]C#: If condition in Linq where clause

我有這樣的Linq查詢...

var path = paths.Where(p=>input_path.ToUpper().Contains(p.ToUpper()).Select(p);

我在paths變量中有C:\\volume1C:\\volume10 input_path可能值為

"C:\volume1"
"C:\volume1\myFolder\myfile.txt"
"C:\volume10"
"C:\volume10\myFolder\myfile.txt"

如果將input_path設置為C:\\volume10\\myFolder\\myfile.txt ,則通過上述查詢,它將向我返回C:\\volume1 ,其中我期望使用C:\\volume10 我想檢查以下內容

var path = paths.Where(p=>input_path.ToUpper().Contains(p.ToUpper()) && (if input_path.length > p.length then if input_path[p.length] == '\\') ).Select(p);

如何使用Linq進行操作? 僅當input_path長度大於path長度時,才應進行“ \\”字符檢查。

編輯:“路徑”僅包含驅動器號和第一級目錄,其中,“ input_path”可以包含多級目錄。

LINQ方法中的lambda可以具有兩種語法- 表達式語句

表達式是求值的東西。 例如,這是您可以在任務右側獲得的內容,默認情況下,這就是lambda中的內容。 如果要使用復雜的表達式,可以使用&&或||之類的邏輯運算符 或?:三元數,將條件組合為一個復合邏輯表達式,其結果為True或False。

paths.Where (p => input_path.Contains(p) 
           && (input_path.Length > p.Length && input_path[p.length] == '\\'))

另外,您可以通過將代碼封裝在一組{}中來使用lambda語句 ,然后可以編寫整個語句塊,並使用return返回值:

paths.Where(p => 
    { 
        if (input_path.Contains(p))
           if (input_path.length > p)
              if (input_path[p.length] = '\\')
              {
                  return true;
              }
        return false;
    }

盡管在您的情況下,該語句的語法還是非常人為設計的,並且第一個似乎最簡單。

如果僅在input_path的子文件夾中需要路徑,則可以簡單地檢查路徑是否以輸入路徑開頭(必要時在末尾添加“ \\”)

input_path = input_path.EndsWith('\\') ? input_path : input_path + '\\';
var path = paths.Where(p=> p.ToUpper().StartsWith(input_path.ToUpper())).Select(p);
         `

您可以嘗試以下方法:

var path = paths.Where(p => input_path.ToUpper().Contains(p.ToUpper()) 
           && (input_path.Length > p.Length  && input_path[p.Length] == '\\'));

僅當input_path.Length> p.Length為true時,才會檢查input_path [p.Length] =='\\'條件。

這應該為你做

var path = paths.Where(p => input_path.ToUpper().Contains(p.ToUpper()) && (input_path.length > p.length && input_path[p.length] == '\\'))
                .Select(p => p);

我會做幾件事:

  1. 擺脫Where並使用Select代碼要快一些(且鍵入更少)
  2. 如果您始終在比較字符串的開頭,請使用StartsWith而不是Contains (和ToUpper )。 StartsWith需要一個比較器,因此您可以指定它忽略大小寫

// Rules: 
// if input_path is longer than path, then see if it begins with path 
// (case-insensitive) and check for the backslash character
// otherwise, the two strings should be equal (case-insensitive)
var path = paths.Select(p =>
    (input_path.Length > p.Length &&
        input_path.StartsWith(p, StringComparison.OrdinalIgnoreCase) &&
        input_path[p.Length] == '\\') ||
    input_path.Equals(p, StringComparison.OrdinalIgnoreCase));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM