You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改查询语句以排除空白或空值?附相关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 where SubDepartment falls into these invalid categories:
    • null (no value stored in the column)
    • Empty string ("")
    • String containing only whitespace (" ")
  • Order of operations: Applying the Where filter before Select and Distinct means 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 your SubDepartmentViewModel uses reference equality (the default), Distinct() might not work as expected if multiple instances have the same SubDepartmentName. To fix this, you can either:
    • Override Equals and GetHashCode in SubDepartmentViewModel to compare SubDepartmentName, or
    • Use .DistinctBy(a => a.SubDepartmentName) (available in .NET 6+) to target the property directly for uniqueness checks.

This should give you a clean list of unique, valid subdepartment names with no empty or null entries!

内容的提问来源于stack exchange,提问作者Renan Siomon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:03:12