LINQ to SQL 查詢返回結果含「空白行」(關鍵字段為空串或空白字符),需在查詢層面過濾。
// 假設實體類有 Name 字段
var validData = db.Table
.Where(x => !string.IsNullOrWhiteSpace(x.Name)) // 核心:IsNullOrWhiteSpace
.ToList();
| 方法 | null | "" | " " | "\t\n" | "abc" |
|---|---|---|---|---|---|
| x.Name != null | false | true | true | true | true |
| x.Name != "" | 異常 | false | true | true | true |
| !string.IsNullOrEmpty(x.Name) | false | false | true | true | true |
| !string.IsNullOrWhiteSpace(x.Name) | false | false | false | false | true |
// IsNullOrWhiteSpace 會轉譯為類似:
WHERE (Name IS NOT NULL) AND (LTRIM(RTRIM(Name)) <> '')
在數據庫端完成過濾,避免拉取大量無效數據到內存。
var valid = db.Table.Where(x =>
!string.IsNullOrWhiteSpace(x.Field1) &&
!string.IsNullOrWhiteSpace(x.Field2)
).ToList();
public static class QueryableExtensions {
public static IQueryable WhereNotBlank(this IQueryable src, Expression> selector) {
return src.Where(x => !string.IsNullOrWhiteSpace(selector.Compile()(x)));
}
}
// 用法
var q = db.Table.WhereNotBlank(x => x.Name);
string.IsNullOrWhiteSpace 是 .NET 4.0+ 標準庫方法,一行代碼解決 null/空串/空白字符串三合一判斷,LINQ to SQL 完美支持翻譯為 SQL。