Convert generic List/Enumerable to DataTable?

后端 未结 27 2573
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  耶瑟儿~
    2020-11-21 23:59

    I realize that this has been closed for a while; however, I had a solution to this specific problem but needed a slight twist: the columns and data table needed to be predefined / already instantiated. Then I needed to simply insert the types into the data table.

    So here's an example of what I did:

    public static class Test
    {
        public static void Main()
        {
            var dataTable = new System.Data.DataTable(Guid.NewGuid().ToString());
    
            var columnCode = new DataColumn("Code");
            var columnLength = new DataColumn("Length");
            var columnProduct = new DataColumn("Product");
    
            dataTable.Columns.AddRange(new DataColumn[]
                {
                    columnCode,
                    columnLength,
                    columnProduct
                });
    
            var item = new List();
    
            item.Select(data => new
            {
                data.Id,
                data.Name,
                data.SomeValue
            }).AddToDataTable(dataTable);
        }
    }
    
    static class Extensions
    {
        public static void AddToDataTable(this IEnumerable enumerable, System.Data.DataTable table)
        {
            if (enumerable.FirstOrDefault() == null)
            {
                table.Rows.Add(new[] {string.Empty});
                return;
            }
    
            var properties = enumerable.FirstOrDefault().GetType().GetProperties();
    
            foreach (var item in enumerable)
            {
                var row = table.NewRow();
                foreach (var property in properties)
                {
                    row[property.Name] = item.GetType().InvokeMember(property.Name, BindingFlags.GetProperty, null, item, null);
                }
                table.Rows.Add(row);
            }
        }
    }
    

提交回复
热议问题