public static List<T> ToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
// list의 요소 생성
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
string propName = prop.Name;
// table column에 object의 property가 없으면 continue
if (!table.Columns.Contains(propName)) continue;
// null 값이면 패스 알아서 default값
if (string.IsNullOrEmpty(row[propName].ToString())) continue;
// property 생성
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
// object의 property에 table의 column 값을 타입에 맞게 Set
propertyInfo.SetValue(obj, Convert.ChangeType(row[propName], propertyInfo.PropertyType), null);
} catch(Exception e)
{
// 요소 하나 에러나면 다음 요소로..
Console.WriteLine($"{prop.Name} : {e.Message}");
}
}
// 요소 Add
list.Add(obj);
}
return list;
} catch (Exception) { return null; } // 에러나면 null 반환
}
DataTable을 받았을 때 List로 바로 컨버팅 해주는 함수
정적 클래스 안에 정의 해주면 된다. Helper 라든지.. 해서
Columns에 propName 찾아서 continue 안해주고 그냥 error 처리 해서 넘어가면 시간 많이 걸린다.
걸릴만한 건 알아서 예외처리 해주는 것이 여러모로 좋다.
사용법은
DataTable table = ~;
table.ToList<class>()
매개변수에 this를 걸어주면 따로 Helper.ToList(table)로 쓰는 것이 아니라
직접 table.ToList() 형태가 가능하다.
'SW개발 > c#' 카테고리의 다른 글
[WPF] 모든 에러 발생시 이벤트 발생시키기 (0) | 2023.02.14 |
---|---|
[C#] Logger (0) | 2023.01.31 |
[WPF] LED Light UI 코드 (2) | 2023.01.31 |
[C#] Byte[] to BitmapSource (0) | 2023.01.26 |
Byte[] To Bitmap (0) | 2023.01.26 |