Listeyi DataTable Nesnesine Çevirme - List To DataTable
Merhabalar bu kısa makalede sizlere bir Generic List nesnesini DataTable yapısına nasıl çevirebileceğimizi aşağıdaki örneklerle anlatmak istiyorum.
Aşağıdaki ListToDataTable metodu ile tüm generic list nesnelerinizi DataTable nesnesine çevirebilirsiniz.
public static DataTable ListToDataTable<T>(this List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Setting column names as Property names dataTable.Columns.Add(prop.Name,prop.PropertyType); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; }
Aynı şekilde aşağıdaki kısa kod bloğunu da Generic List nesnelerinizi DataTable nesnesine çevirebilirsiniz.
public static List<T> ConvertDataTable<T>(this DataTable dt) { List<T> data = new List<T>(); foreach (DataRow row in dt.Rows) { T item = GetItem<T>(row); data.Add(item); } return data; }
0 Yorumlar
Yorumunuz için çok teşekkür ederim. En kısa zamanda geri dönüş yapacağım.