DataTable Nesnesini Listeye Çevirme - DataTable To List
Merhabalar bu kısa makalede sizlere bir DataTable nesnesini Generic List’e nasıl çevirebileceğimizi içeren örnekler paylaşacağım.
DataTable To List metodu ile bir DataTable nesnesini eşleştirilebilen bir sınıfa çevirebilirsiniz.
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new() { try { List<T> list = new List<T>(); foreach (var row in table.AsEnumerable()) { T obj = new T(); foreach (var prop in obj.GetType().GetProperties()) { try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } catch { continue; } } list.Add(obj); } return list; } catch { return null; } }
Aşağıdaki kod bloğunda da aynı şekilde eşleşebilen bir sınıfa DataTable nesnesini aktarabilirsiniz.
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.