(에센스) 2020년 6월 26일 C# 라이브러리 ExpandoObject(확장 방법)

using System; using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; namespace Core.Util { public static partial class Extention { /// /// /// /// /// /// public static void AddProperty(this ExpandoObject expandoObj,string propertyName,object value) { var obj = (IDictionary<string, object>)expandoObj; if (obj.ContainsKey(propertyName)) throw new Exception(" !"); else obj.Add(propertyName, value); } /// /// /// /// /// /// public static void SetProperty(this ExpandoObject expandoObj, string propertyName, object value) { var obj = (IDictionary<string, object>)expandoObj; if (!obj.ContainsKey(propertyName)) obj.Add(propertyName, value); else obj[propertyName] = value; } /// /// /// /// /// /// public static object GetProperty(this ExpandoObject expandoObj, string propertyName) { var obj = (IDictionary<string, object>)expandoObj; if (!obj.ContainsKey(propertyName)) throw new Exception(" !"); else return obj[propertyName]; } /// /// /// /// /// public static List<string> GetProperties(this ExpandoObject expandoObj) { var obj = (IDictionary<string, object>)expandoObj; return obj.Keys.CastToList<string>(); } /// /// /// /// /// public static void RemoveProperty(this ExpandoObject expandoObj, string propertyName) { var obj = (IDictionary<string, object>)expandoObj; if (!obj.ContainsKey(propertyName)) throw new Exception(" !"); else obj.Remove(propertyName); } /// /// ExpandoObject DataTable /// /// /// public static DataTable ToDataTable(this IEnumerable<ExpandoObject> dataList) { DataTable dt = new DataTable(); if (dataList.IsNullOrEmpty()) return null; else if (dataList.Count() == 0) return dt; else { var aEntity = dataList.FirstOrDefault(); var properties = aEntity.GetProperties(); properties.ForEach(aProperty => { dt.Columns.Add(aProperty); }); dataList.ForEach((aData,index) => { dt.Rows.Add(dt.NewRow()); properties.ForEach(aProperty => { dt.Rows[index][aProperty] = aData.GetProperty(aProperty); }); }); } return dt; } } }

좋은 웹페이지 즐겨찾기