c# – Listeyi DataTable dönüştürmek(ConvertToDataTable)

24 Mar

Merhaba arkadaşlar, Elimizde ki bir listeyi, dataTable dönüştürmek için aşağıda ki kodları kullanmamız yeterlidir. Kütüphaneye using System.Reflection; eklemeyi unutmayalım. Kaynak :stackoverflow Herhangi bir tipte ki listeyi, bu methoda göndermemiz yeterli oluyor. Gönderdiğimiz liste geriye DataTable olarak dönüyor. public static System.Data.DataTable ConvertToDataTable(List items)         {             System.Data.DataTable dataTable = new System.Data.DataTable(typeof(T).Name);             //Get all the properties             PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);             foreach (PropertyInfo prop in Props)             {                 //Defining type of data column gives proper data table                  var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);                 //Setting column names as Property names                 dataTable.Columns.Add(prop.Name, type);             }             foreach (T item in items) … Read More »