【问题标题】:Get all column names of all datatable properties from a class从一个类中获取所有数据表属性的所有列名
【发布时间】:2021-06-23 15:14:55
【问题描述】:

我有一个像下面这样的课程。它有多个 DataTable 类型的属性。我正在尝试动态获取所有属性并打印它们的列名。

public class Example
{
    public DataTable dt1 { get; set; }
    public DataTable dt2 { get; set; }
    ...
    public DataTable dtN { get; set; }
} 

预期输出:

表 1 名称:dt1
表 1 列:col_11、col_12、col_13

表 2 名称:dt2
表 2 列:col_21、col_22、col_23

...

TableN 名称:dtN
TableN 列:col_N1、col_N2、col_N3

【问题讨论】:

  • “我想...”很高兴知道。介意与我们分享您已经走了多远?

标签: c# .net .net-core


【解决方案1】:

假设您有一个Example 类型的对象ex,您可以通过以下方式找到所有属性的列名:

Type exType = ex.GetType();
List<PropertyInfo> props = new List<PropertyInfo>(exType.GetProperties());
foreach(PropertyInfo prop in props) {
    DataTable thisDT = (DataTable)prop.GetValue(ex);
    var tableName = prop.Name;
    var columnNames = new List<string>();
    foreach(DataColumn column in thisDT.Columns) {
        columnNames.Add(column.Name);
    }
    Console.WriteLine($"Table Name: {tableName}");
    Console.WriteLine($"Column Names: {String.Join(",", columnNames)}");
}

注意:这里假设 Example 中的每个属性都是 DataTables。如果没有,您需要在foreach(PropertyInfo prop in props) 循环中做更多的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多