簡體   English   中英

如何使用Linq從DataTable Where中選擇*

[英]How to select * from DataTable Where… using Linq

我正在嘗試使用linq過濾數據表,我嘗試這樣做。

string strFind = "Road";
var query = from a in res.AsEnumerable()
             where (a.Field<string>("Last Name") == strFind || 
             a.Field<string>("First Name") == strFind ||
             a.Field<string>("Address") == strFind)                  
             select a;

我還有大約5列需要過濾掉,目前正在測試代碼以查看它是否可以正常工作。 我嘗試將數據表放到列表中,並使用.Contains(strFind)進行過濾,但這對我也不可行。

LINQ查詢實際上對您要查詢的列表沒有任何作用。 該查詢為您提供了結果列表。 如果希望用戶看到這些結果,則必須實際顯示這些結果,例如,調用ToArrayToList或者在這種情況下, CopyToDataTable ,然后將結果綁定到網格或其他對象。

它也可以工作:

   var query = res.AsEnumerable()
         where (a.Field<string>("Last Name") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase) || 
         a.Field<string>("First Name") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase) || 
         a.Field<string>("Address") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase) 
         ).ToList()

使用以下擴展方法來解決strFind中的區分大小寫

 public static bool CustomContains(this string source, string toCheck, StringComparison compare)
    {
        return source.IndexOf(toCheck, compare) >= 0;

    }

暫無
暫無

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

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