首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> DB2 資料庫 >> DB2 教學

LINQ 查詢 DataTable 記錄集合:字串範圍過濾與匿名型別投射

     編輯:DB2 教學

LINQ 查詢 DataTable 記錄集合:字串範圍過濾與匿名型別投射

本文示範使用 LINQ to DataTable 依字串欄位進行範圍過濾,並投射匿名型別輸出指定欄位。注意:字串比較存在字典序陷阱,實務上優先轉型數值比較。

基本範例(字串比較)

string strDepth = "查詢深度的值";

var dataRows = from row in dataTable.AsEnumerable()
               where string.Compare(row.Field("深度欄位"), strDepth) >= 0
                  && string.Compare(row.Field("深度欄位"), strDepth) <= 0
               select new {
                 Depth = row["深度欄位"].ToString()
               };

修正:數值轉型比較(推薦)

var dataRows = from row in dataTable.AsEnumerable()
               let depth = row.Field("深度欄位")
               where depth >= 100 && depth <= 200
               select new { Depth = depth };

動態欄位與條件

public static IEnumerable RangeFilter(DataTable dt, string column, decimal min, decimal max) {
  return dt.AsEnumerable()
           .Where(r => {
             var val = r.Field(column);
             return val >= min && val <= max;
           });
}

效能與適用場景

  • 記憶體中 LINQ 適合 < 10 萬列;大資料量請下推 SQL 或用 DataView.RowFilter。
  • 使用 let 避免重複 Field<T>() 呼叫。
  • 匿名型別僅限方法內部使用,跨層傳遞請定義 DTO/Record。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved