使用“对象属性”动态填充DataTable

时间:2015-03-18 10:38:43

标签: c# datatable

我试图以动态方式将对象属性添加到数据表中。我试图远离显式声明对象的属性,因为我希望此代码适用于我的应用程序中的每个对象。  我已经阅读了Adding object to DataTable and create a dynamic GridView,但这对我来说不够动态,因为他明确指定了属性。

private static void Main(string[] args)
        {
            //Read in JSON from text file
            StreamReader fileStream = new StreamReader(@"C:\Users\Aid\Desktop\test.txt");
            string json = fileStream.ReadToEnd();

            //Deserialise and map to class
            Client u = JsonConvert.DeserializeObject<Client>(json);

            DataTable dt = new DataTable();

            List<string> CliProperties = new List<string>();
            //Loop through Object properties and add to Datatable columns
            CliProperties = objProps(u);

            DataRow newRow = dt.NewRow();
            foreach (var prop in CliProperties)
            {
                dt.Columns.Add(prop);
                newRow[prop] = u.prop;
            }

            Console.ReadKey();
        }



        /// <summary>
        /// Get list of object properties
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<string> objProps(Object obj)
        {
            List<string> Props = new List<string>();

            Type objType = obj.GetType();
            foreach (PropertyInfo propertyInfo in objType.GetProperties())
            {
                if (propertyInfo.CanRead)
                {
                    Props.Add(propertyInfo.Name);
                }
            }
            return Props;
        }
    }

    public static class DataColumnCollectionExtensions
    {
        public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
        {
            return source.Cast<DataColumn>();
        }
    }

我的问题是:

foreach (var prop in CliProperties)
            {
                dt.Columns.Add(prop);
                newRow[prop] = u.prop;
            }

我收到错误:'Client' does not contain a definition for 'prop' and no extension method 'prop' accepting first argument of type 'Client'

我理解为什么我会收到错误,但我不确定如何使其发挥作用。

我尝试使用对象属性值newRow[prop]的值添加PropertyName = u.prop的新行。

编辑:DataTable列名称将与对象属性名称相同。

foreach的第一次迭代应该如下:

foreach (var prop in CliProperties)
{
    dt.Columns.Add("RefID");
    newRow["RefID"] = u.RefID;
}

1 个答案:

答案 0 :(得分:3)

使用针对列表的此扩展方法,将User对象设为List<User>,然后只需在其实例上调用ToDataTable()

这是扩展方法:

public static class ListExtensions
{
   public static DataTable ToDataTable<T>(this List<T> iList)
   {
    DataTable dataTable = new DataTable();
    PropertyDescriptorCollection propertyDescriptorCollection =
        TypeDescriptor.GetProperties(typeof(T));
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        dataTable.Columns.Add(propertyDescriptor.Name, type);
    }
    object[] values = new object[propertyDescriptorCollection.Count];
    foreach (T iListItem in iList)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
        }
        dataTable.Rows.Add(values);
    }
    return dataTable;
  }
}

你必须简单地这样说:

List<User> users = new List<User>();
DataTable dt = users.ToDataTable();

UPDATE:

您的方式必须迭代User类属性,如下所示:

PropertyDescriptorCollection propertyDescriptorCollection =
        TypeDescriptor.GetProperties(typeof(User));
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        dt.Columns.Add(propertyDescriptor.Name, type);
    }

刚刚为Class的单个对象编写了另一种扩展方法:

public static DataTable ToDataTable<T>(this T Item) where T: class
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];

                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(Item);
                }

                dataTable.Rows.Add(values);

            return dataTable;
        }

并将其称为:

Client u = JsonConvert.DeserializeObject<Client>(json);
DataTable dt = user.ToDataTable();