Created
January 8, 2021 17:10
-
-
Save gcapnias/4fa6251f285c85eb1cbfd13f214fa7e2 to your computer and use it in GitHub Desktop.
Convert an IList<T> to DataTable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static partial class Extensions | |
| { | |
| public static DataTable ToDataTable<T>(this IList<T> data) | |
| { | |
| PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); | |
| DataTable table = new DataTable(); | |
| for (int i = 0; i < props.Count; i++) | |
| { | |
| PropertyDescriptor prop = props[i]; | |
| DataColumn column = table.Columns.Add(prop.Name, prop.PropertyType); | |
| var displayname = prop.Attributes.OfType<DisplayNameAttribute>().FirstOrDefault(); | |
| if (displayname != null) | |
| { | |
| column.Caption = displayname.DisplayName; | |
| } | |
| } | |
| object[] values = new object[props.Count]; | |
| foreach (T item in data) | |
| { | |
| for (int i = 0; i < values.Length; i++) | |
| { | |
| values[i] = props[i].GetValue(item); | |
| } | |
| table.Rows.Add(values); | |
| } | |
| return table; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment