将对象转化为DataTable

Imports System.Collections.Generic
Imports System.Reflection

Public Class TableBuilder(Of T)
    Private selectInfos As List(Of PropertyInfo)
    Private propInfos As PropertyInfo()

    Sub New()
        selectInfos = New List(Of PropertyInfo)
        propInfos = GetType(T).GetProperties
    End Sub

    Public Sub SetPropertyNames(ByVal names() As String)
        selectInfos.Clear()
        If names IsNot Nothing AndAlso names.Count > 0 Then
            For Each p As PropertyInfo In propInfos
                If names.Contains(p.Name) Then
                    selectInfos.Add(p)
                End If
            Next
        End If
    End Sub

    Public Function CreateTable() As DataTable
        Dim table As New DataTable
        If selectInfos.Count = 0 Then
            selectInfos.AddRange(propInfos)
        End If
        For Each p As PropertyInfo In selectInfos
            table.Columns.Add(p.Name, GetType(String))
        Next
        Return table
    End Function

    Public Function ToDataTable(ByVal items As IEnumerable(Of T)) As DataTable
        Dim table As DataTable = CreateTable()
        Dim tempList As New List(Of String)
        For Each item As T In items
            For Each p As PropertyInfo In selectInfos
                Dim value As Object = p.GetValue(item, Nothing)
                If value IsNot Nothing Then
                    tempList.Add(value.ToString)
                Else
                    tempList.Add(String.Empty)
                End If
            Next
            table.Rows.Add(tempList.ToArray)
            tempList.Clear()
        Next
        Return table
    End Function
End Class



using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace DAL
{
    /// <summary>
    /// DataTable响应通用解释器。
    /// </summary>
    public class DataTableParser<T>
    {
        private static Regex numRegex = new Regex("Int32|Int64|Integer|Long|Double", RegexOptions.Compiled);
        private string[] props;

        private List<string> propNames = new List<string>();
        public DataTableParser()
        {
            List<string> ps = new List<string>();
            foreach (PropertyInfo p in typeof(T).GetProperties())
            {
                ps.Add(p.Name);
            }
            props = ps.ToArray();
            //props = (from PropertyInfo p in typeof(T).GetProperties() select p.Name).ToArray;
        }

        /// <summary>
        /// 设置属性名称
        /// </summary>
        public void SetNames(DataColumnCollection columns)
        {
            propNames.Clear();
            foreach (string prop in props)
            {
                if (columns.Contains(prop))
                {
                    propNames.Add(prop);
                }
            }
        }

        /// <summary>
        /// 设置属性名称
        /// </summary>
        public void SetNames(params string[] names)
        {
            propNames.Clear();
            foreach (string prop in props)
            {
                foreach (string name in names)
                {
                    if (name == prop)
                        propNames.Add(prop);
                }
            }
        }

        /// <summary>
        /// 把DataTable解释成相应的领域对象。
        /// </summary>
        /// <param name="table">要解析的DataTable</param>
        /// <returns>领域对象</returns>
        public List<T> Parse(DataTable table)
        {
            SetNames(table.Columns);
            List<T> list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                //On Error Resume Next
                T obj = Activator.CreateInstance<T>();
                foreach (string name in propNames)
                {
                    PropertyInfo p = typeof(T).GetProperty(name);
                    SetTopValue(p, ref obj, row[name]);
                }
                list.Add(obj);
            }
            return list;
        }

        /// <summary>
        /// 把DataRow解释成相应的领域对象。
        /// </summary>
        /// <param name="row">要解析的DataRow</param>
        /// <returns>领域对象</returns>
        public T Parse(DataRow row)
        {
            T obj = Activator.CreateInstance<T>();
            foreach (string name in propNames)
            {
                PropertyInfo p = typeof(T).GetProperty(name);
                SetTopValue(p, ref obj, row[name]);
            }
            return obj;
        }

        /// <summary>
        /// 支持:string, int, long, double, boolean, dateTime类型
        /// </summary>
        private static void SetTopValue(PropertyInfo p, ref T obj, object value)
        {
            if (value == null)
                return;
            if (!value.GetType().Equals(p.PropertyType))
            {
                string fullName = p.PropertyType.FullName;
                if (p.PropertyType.Equals(typeof(string)))
                {
                    p.SetValue(obj, value.ToString(), null);
                }
                else if (fullName.Contains("DateTime"))
                {
                    DateTime v = Convert.ToDateTime(value);
                    p.SetValue(obj, v, null);
                }
                else if (fullName.Contains("Boolean"))
                {
                    bool v = Convert.ToBoolean(value);
                    p.SetValue(obj, v, null);
                }
                else if (numRegex.IsMatch(fullName))
                {
                    long v = Convert.ToInt64(value);
                    p.SetValue(obj, v, null);
                }
            }
            else
            {
                p.SetValue(obj, value, null);
            }
        }
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值