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

C#:如何依据指定列列表筛选对象属性值生成目标数组

问题描述

现有选中列列表:

IList<string> selectedColumn = new List<string>{"Name", "City", "CreatedAt"};

遍历Car对象集合时,当前代码提取了多个属性值:

foreach (Car car in rowsWithAllCar)
{
 string name = car.Name;
 string lastName = car.LastName;
 string city = car.City;
 string home = car.Home;     
 DateTime createdAt= (DateTime)car.CreatedAt;

 string[] allItems = {name, lastName, phone, city, createdAt}; // 注:原代码中phone未定义,属于笔误
}

需求:仅将属性名称存在于selectedColumn列表中的属性值加入allItems数组,最终得到:

string[] allItems = {name, city, createdAt};

解决方案

方法一:手动判断(适合属性数量少的场景)

直接针对每个属性做存在性检查,符合条件的加入临时集合,最后转数组:

foreach (Car car in rowsWithAllCar)
{
    var tempList = new List<string>();
    
    if (selectedColumn.Contains("Name"))
        tempList.Add(car.Name);
    
    if (selectedColumn.Contains("LastName"))
        tempList.Add(car.LastName);
    
    if (selectedColumn.Contains("City"))
        tempList.Add(car.City);
    
    if (selectedColumn.Contains("Home"))
        tempList.Add(car.Home);
    
    if (selectedColumn.Contains("CreatedAt"))
        tempList.Add(((DateTime)car.CreatedAt).ToString()); // 可自定义DateTime格式,比如ToString("yyyy-MM-dd")
    
    string[] allItems = tempList.ToArray();
}

这种方式简单直观,无需额外知识,还能灵活控制不同类型属性的转换逻辑。

方法二:反射实现(适合属性多或需动态扩展的场景)

如果Car类属性较多,或者selectedColumn会动态变化,用反射可以避免重复的判断代码:

using System.Reflection;

foreach (Car car in rowsWithAllCar)
{
    var tempList = new List<string>();
    Type carType = typeof(Car);
    
    foreach (string columnName in selectedColumn)
    {
        PropertyInfo prop = carType.GetProperty(columnName);
        if (prop != null)
        {
            object value = prop.GetValue(car);
            // 处理空值和特殊类型转换
            string strValue = value switch
            {
                DateTime dt => dt.ToString("yyyy-MM-dd HH:mm:ss"),
                null => string.Empty,
                _ => value.ToString()
            };
            tempList.Add(strValue);
        }
    }
    
    string[] allItems = tempList.ToArray();
}

这种方式无需修改代码就能适配新增属性,只需保证selectedColumn中的名称与Car类属性名一致即可。如果需要忽略大小写匹配,可以修改反射的获取逻辑:

PropertyInfo prop = carType.GetProperty(columnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

注意事项

  1. 原代码中phone变量未定义,属于笔误,实现时需修正或忽略。
  2. CreatedAt是DateTime类型,必须转换为字符串才能加入字符串数组,可根据业务需求指定格式化规则。
  3. 若selectedColumn与属性名大小写不一致,需在判断或反射时添加忽略大小写的规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:35:34