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

如何获取列表中值为Null的属性名并始终包含InvoiceNumber

获取包含发票号及对应空属性名的列表

需求说明

生成一个结果集,每个条目需始终包含InvoiceNumber,同时列出该发票对象中所有值为null的其他属性名称。示例格式:101| FromDate |ExpenseMethod |(表示发票号101的对象中,FromDate和ExpenseMethod属性值为null)

实体类定义

public class InvoiceDetails
{
     public string InvoiceNumber { get; set; }
     public string InvoiceClass { get; set; }
     public string ExpenseMethod { get; set; }
     public string FromDate { get; set; }
     public string ToDate { get; set; }
}

现有代码的局限

  • 代码#1:仅筛选出存在空值属性的发票号列表,完全丢失了"哪些属性为空"的关键信息。
  • 代码#2:逻辑错误(实际筛选了非空属性),且仅能处理单个对象,无法批量处理集合,也未关联发票号。

解决方案

方案1:反射实现(通用型)

适合属性较多、后续可能新增属性的场景,无需修改代码即可适配新属性:

// 假设invoiceList是你的InvoiceDetails集合
var nullPropertyResults = invoiceList
    .Select(inv => new 
    {
        InvoiceNumber = inv.InvoiceNumber,
        NullPropertyNames = typeof(InvoiceDetails)
            .GetProperties()
            // 排除InvoiceNumber本身,我们要找的是其他空属性
            .Where(p => p.Name != nameof(InvoiceDetails.InvoiceNumber))
            .Where(p => p.GetValue(inv) == null)
            .Select(p => p.Name)
            .ToList()
    })
    // 可选:仅保留存在空属性的条目,按需移除
    .Where(item => item.NullPropertyNames.Any())
    .ToList();

// 转换为需求的字符串格式
var formattedOutput = nullPropertyResults
    .Select(item => $"{item.InvoiceNumber}| {string.Join(" |", item.NullPropertyNames)} |")
    .ToList();

方案2:强类型实现(高性能型)

适合属性固定、追求性能的场景,类型安全且无反射开销:

// 假设invoiceList是你的InvoiceDetails集合
var nullPropertyResults = invoiceList
    .Select(inv => new 
    {
        InvoiceNumber = inv.InvoiceNumber,
        NullPropertyNames = new List<string>()
        {
            inv.InvoiceClass == null ? "InvoiceClass" : null,
            inv.ExpenseMethod == null ? "ExpenseMethod" : null,
            inv.FromDate == null ? "FromDate" : null,
            inv.ToDate == null ? "ToDate" : null
        }.Where(name => name != null).ToList()
    })
    // 可选:仅保留存在空属性的条目,按需移除
    .Where(item => item.NullPropertyNames.Any())
    .ToList();

// 转换为需求的字符串格式
var formattedOutput = nullPropertyResults
    .Select(item => $"{item.InvoiceNumber}| {string.Join(" |", item.NullPropertyNames)} |")
    .ToList();

说明

  • 两种方案都可根据需求调整:若需要保留所有发票(即使没有空属性),只需移除.Where(item => item.NullPropertyNames.Any())这一行。
  • 格式化后的字符串可直接用于输出或存储,完全匹配需求示例格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:15:42