如何在c#中编写数据类型转换扩展方法? [英] How to write data type conversion extended method in c#?

查看:83
本文介绍了如何在c#中编写数据类型转换扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#中编写数据类型转换扩展方法?

有没有办法将数据表数据转换成列表或模型类?请提供示例代码。

How to write data type conversion extended method in c#?
Have any way to convert data table data into list or model class? Please provided with sample code.

推荐答案

您好



使用此实用程序将Datatable转换为Generic List



如果您的DataTable列与Class Property Name不同,您可以使用该属性来匹配列。

Hi

Use this Utility for converting Datatable to Generic List

If your DataTable Column is not same as the Class Property Name u can use the attribute to match the column.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;

namespace  Helper
{
    public class GenericUtility
    {
        public static List<t> DataTableToList<t>(DataTable dt) where T : class, new()
        {
            List<t> lstItems = new List<t>();
            if (dt != null && dt.Rows.Count > 0)
                foreach (DataRow row in dt.Rows)
                    lstItems.Add(ConvertDataRowToGenericType<t>(row));
            else
                lstItems = null;
            return lstItems;
        }

        private static T ConvertDataRowToGenericType<t>(DataRow row) where T : class,new()
        {
            Type entityType = typeof(T);
            T objEntity = new T();
            foreach (DataColumn column in row.Table.Columns)
            {
                object value = row[column.ColumnName];
                if (value == DBNull.Value) value = null;
                PropertyInfo property = entityType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
                try
                {
                    if (property != null && property.CanWrite)
                        property.SetValue(objEntity, value, null);
                    else
                    {
                        property = entityType.GetProperties().Where(k => k.GetCustomAttributes(typeof(SQLInfoAttribute), true).Length > 0).SingleOrDefault(k => ((SQLInfoAttribute)k.GetCustomAttributes(typeof(SQLInfoAttribute), true)[0]).ColumnName == column.ColumnName);
                        if (property != null)
                            property.SetValue(objEntity, value, null);
                    }
                }
                catch (Exception ex)
                {
                    string exceptionMessageInfo_Names = string.Format("SQL Column Name:= {0} \n BusinessType Property Name:= {1}", column.ColumnName, property != null ? property.Name : string.Empty);
                    string exceptionMessageInfo_DataTypes = string.Format("SQL Column Type:= {0} \n BusinessType Property Type:= {1}", column.DataType, property != null ? property.PropertyType.Name : string.Empty);
                    throw new Exception("Error Message := " + ex.Message + Environment.NewLine + exceptionMessageInfo_Names +
                    Environment.NewLine + exceptionMessageInfo_DataTypes);
                }
            }
            return objEntity;
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class SQLInfoAttribute : Attribute
    {
        public string ColumnName;
        public SQLInfoAttribute(string columnName) { ColumnName = columnName; }

    }
}


看到这个

数据类型转换的扩展方法

和转换数据表到列表中

see this
Extension Methods for Data Type Conversion
and to Convert data table into list
Try 
List<object> lst = dt.AsEnumerable().ToList<object>();
// or 
IEnumerable<object> something= dt.AsEnumerable();


请参阅此示例并准备好解决方案:





http://dotnetext.codeplex.com/ [ ^ ]
See this for examples and ready to go solutions:


http://dotnetext.codeplex.com/[^]


这篇关于如何在c#中编写数据类型转换扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆