Convert generic List/Enumerable to DataTable?

后端 未结 27 2148
臣服心动
臣服心动 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:57

    If you want to use reflection and set columns order/ include only some columns/ Exclude some columns try this:

            private static DataTable ConvertToDataTable(IList data, string[] fieldsToInclude = null,
    string[] fieldsToExclude = null)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
                    (fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
                    continue;
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
    
            foreach (T item in data)
            {
                var atLeastOnePropertyExists = false;
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
    
                    if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
    (fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
                        continue;
    
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                    atLeastOnePropertyExists = true;
                }
    
                if(atLeastOnePropertyExists) table.Rows.Add(row);
            }
    
    
            if (fieldsToInclude != null)
                SetColumnsOrder(table, fieldsToInclude);
    
            return table;
    
        }
    
        private static void SetColumnsOrder(DataTable table, params String[] columnNames)
        {
            int columnIndex = 0;
            foreach (var columnName in columnNames)
            {
                table.Columns[columnName].SetOrdinal(columnIndex);
                columnIndex++;
            }
        }
    

提交回复
热议问题