如何修改查询语句以排除空白或空值?附相关C#查询代码
Fix: Exclude Null/Blank Values from Distinct SubDepartment Query
Hey there! To tweak your existing query so it returns only distinct, non-null, non-blank subdepartment names, we’ll add a filter early on (this is more efficient too, since we trim down the dataset before processing unique values).
Here’s the updated code:
public List<SubDepartmentViewModel> GetSubDepartments() { var query = _db.SendersReceivers // Filter out invalid values first: null, empty, or whitespace-only strings .Where(a => !string.IsNullOrWhiteSpace(a.SubDepartment)) .Select(a => new SubDepartmentViewModel { SubDepartmentName = a.SubDepartment }) .Distinct() .ToList(); return query; }
Key Changes Breakdown:
Where(a => !string.IsNullOrWhiteSpace(a.SubDepartment)): This line removes any records whereSubDepartmentfalls into these invalid categories:null(no value stored in the column)- Empty string (
"") - String containing only whitespace (
" ")
- Order of operations: Applying the
Wherefilter beforeSelectandDistinctmeans we only process records with valid subdepartment names right off the bat — way more performant than filtering after generating the view models. - Quick note about
Distinct(): If yourSubDepartmentViewModeluses reference equality (the default),Distinct()might not work as expected if multiple instances have the sameSubDepartmentName. To fix this, you can either:- Override
EqualsandGetHashCodeinSubDepartmentViewModelto compareSubDepartmentName, or - Use
.DistinctBy(a => a.SubDepartmentName)(available in .NET 6+) to target the property directly for uniqueness checks.
- Override
This should give you a clean list of unique, valid subdepartment names with no empty or null entries!
内容的提问来源于stack exchange,提问作者Renan Siomon
相关产品推荐
相关产品推荐

