如何从数据表动态转换为对象数组 [英] How To dynamically convert to object array from data table

查看:90
本文介绍了如何从数据表动态转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI 我知道使用数据表转换为对象数组的最简单方法.我想要它在另一个函数中执行的功能将动态转换为对象.像这样的东西---

HI I know the simplest way to convert to object array using datatable. All i want it to do in another function which will dynamically convert to object. Something like this---

public class clsBindObjectUsingDataTable
    {
        private int intCount;
        private List<object> objList;
        public void BindObject(object[] objMyObjectList, DataTable dttable)
        {
            objList = new List<object>(typeof(objMyObjectList));//to get property //of the object 
            objList = objMyObjectList.ToList();
            foreach (DataRow drRow in dttable.Rows)
            {
                intCount = drRow .ItemArray.Length;
                for (int i = 0; i < intCount;i++ )
                {
                    objList[0][i].Add(drRow.ItemArray[i]); ///i know this doesnt work 
//just wanted to give my idea
                }
                //objList.Add(drRow.ItemArray);                
            }
            objMyObjectList = objList.ToArray();
        }
    }

推荐答案

查看本文使用反射将DataRows转换为对象或将对象转换为DataRows

您可能还想尝试这种扩展方法:

Look at this article Using Reflection to convert DataRows to objects or objects to DataRows

You might want to try this extension method also :

ObjectArray[] objectArray = DataSet.ToSpecifiedObject<ObjectArray[]>();

public static T ToSpecifiedObject<T>(this DataSet value)
{
    byte[] buf = System.Text.UTF8Encoding.UTF8.GetBytes(value.GetXml());
    MemoryStream ms = new MemoryStream(buf);
    XmlSerializer ser = new XmlSerializer(typeof(T));
    object obj = ser.Deserialize(ms);

    return (T)obj;
}


这篇关于如何从数据表动态转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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