Convert DataTable to Generic List in C#

后端 未结 9 1284
既然无缘
既然无缘 2020-12-01 01:28

Disclaimer: I know its asked at so many places at SO.
My query is a little different.

Coding Language: C# 3.5

I have a DataTable named cardsTable that

9条回答
  •  一向
    一向 (楼主)
    2020-12-01 02:29

    Coming late but this can be useful. Can be called using:

    table.Map(); or call with a Func to filter the values.

    You can even change the mapping name between the type property and DataColumn header by setting the attributes on the property.

    [AttributeUsage(AttributeTargets.Property)]
        public class SimppleMapperAttribute: Attribute
        {
            public string HeaderName { get; set; }
        }
    
    
         public static class SimpleMapper
    {
        #region properties
        public static bool UseDeferredExecution { get; set; } = true;
        #endregion
    
    #region public_interface  
    
    
        public static IEnumerable MapWhere(this DataTable table, Func sortExpression) where T:new()
        {
            var result = table.Select().Select(row => ConvertRow(row, table.Columns, typeof(T).GetProperties())).Where((t)=>sortExpression(t));
            return UseDeferredExecution ? result : result.ToArray();
        }
        public static IEnumerable Map(this DataTable table) where T : new()
        {
            var result = table.Select().Select(row => ConvertRow(row, table.Columns, typeof(T).GetProperties()));
            return UseDeferredExecution ? result : result.ToArray();
        }
        #endregion
    
    #region implementation_details
        private static T ConvertRow(DataRow row, DataColumnCollection columns, System.Reflection.PropertyInfo[] p_info) where T : new()
        {
            var instance = new T();
            foreach (var info in p_info)
            {
                if (columns.Contains(GetMappingName(info))) SetProperty(row, instance, info);             
            }
            return instance;
        }
    
        private static void SetProperty(DataRow row, T instance, System.Reflection.PropertyInfo info) where T : new()
        {
            string mp_name = GetMappingName(info);
            object value = row[mp_name];
            info.SetValue(instance, value);
        }
    
        private static string GetMappingName(System.Reflection.PropertyInfo info)
        {
            SimppleMapperAttribute attribute = info.GetCustomAttributes(typeof(SimppleMapperAttribute),true).Select((o) => o as SimppleMapperAttribute).FirstOrDefault();
            return attribute == null ? info.Name : attribute.HeaderName;
        }
    #endregion
    }
    

提交回复
热议问题