本文示範使用 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 IEnumerableRangeFilter(DataTable dt, string column, decimal min, decimal max) { return dt.AsEnumerable() .Where(r => { var val = r.Field (column); return val >= min && val <= max; }); }
DataView.RowFilter。let 避免重複 Field<T>() 呼叫。