如何从TopProducts集合提取DataTable属性并生成List<DataTable>
提取TopProducts集合中所有DataTable属性的实现方法
要实现遍历TopProducts集合,提取每个实例中所有DataTable类型的属性并生成List<DataTable>,可以通过反射来实现,不用硬编码每个属性名,后续新增DataTable属性也无需修改这段逻辑。
基础实现代码
public List<DataTable> GetListOfDataTables(List<TopProducts> ProductList) { List<DataTable> dtList = new List<DataTable>(); // 获取TopProducts类中所有DataTable类型的属性 var dataTableProps = typeof(TopProducts).GetProperties() .Where(p => p.PropertyType == typeof(DataTable)) .ToList(); foreach (TopProducts product in ProductList) { foreach (var prop in dataTableProps) { // 获取当前属性的值,转成DataTable DataTable dt = prop.GetValue(product) as DataTable; // 避免添加null值(如果属性未初始化) if (dt != null) { dtList.Add(dt); } } } return dtList; }
LINQ简化版本
如果偏好更简洁的写法,可以用LINQ链式调用完成:
public List<DataTable> GetListOfDataTables(List<TopProducts> ProductList) { var dataTableProps = typeof(TopProducts).GetProperties() .Where(p => p.PropertyType == typeof(DataTable)); return ProductList .SelectMany(product => dataTableProps.Select(prop => prop.GetValue(product) as DataTable)) .Where(dt => dt != null) .ToList(); }
注意事项
- 上述代码会自动包含
TopProducts类中所有DataTable类型的属性,后续新增相关属性无需修改提取逻辑。 - 添加了
null检查,避免将未初始化的DataTable属性(值为null)加入列表,防止后续操作出现空引用异常。
内容的提问来源于stack exchange,提问作者Gokhan
相关产品推荐
相关产品推荐

