简体   繁体   English

如何将DataTable行集合反序列化为列表<T>

[英]How do I deserialize DataTable Rows Collection into List<T>

A few days back I had to de-serialize data from xml file to my List class. 几天前,我不得不将数据从xml文件反序列化到我的List类。 my approach was like this: 我的方法是这样的:

private void button1_Click(object sender, EventArgs e)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("Test.xml");
    XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
    UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(doc.OuterXml));
    dataGridView1.DataSource = uh.Users.ToDataTable();
}
public class User
{
    [XmlElement("id")]
    public Int32 Id { get; set; }

    [XmlElement("name")]
    public String Name { get; set; }
}

[XmlRoot("user_list")]
public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
        users = new List<User>(); 
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

public static class Convert2Table
{
    public static DataTable ToDataTable<T>(this IList<T> list)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in list)
        {
            for (int i = 0; i < values.Length; i++)
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            table.Rows.Add(values);
        }
        return table;
    }
}

The code above works fine, but I had to write many lines of code. 上面的代码工作正常,但是我不得不写很多行代码。

I now have a new situation where I have a customer class and one datatable. 我现在有一个新情况,我有一个客户类别和一个数据表。 My datatable is populated with multiple customers data. 我的数据表中填充了多个客户数据。 I want to deserialize that data from datatable to my customer class. 我想将该数据从数据表反序列化到我的客户类别。 How can I do that more efficiently than I did before? 我如何比以前更有效地做到这一点? I doubt linq will help me. 我怀疑linq会帮助我。 So please guide me for deserialize datatable data to my customer class List. 因此,请指导我将数据表数据反序列化到我的客户类别列表中。

Like this: 像这样:

DataTable dt .... 


List<Customer>  customers = (from c in dt.AsEnumerable()
                select new Customer { ID = c.Field<int>("CustomerID"), 
                Name=c.Field<string>("CustomerName")  }).ToList();

And so on for all the properties of Customer 对于Customer所有属性,依此类推

Probably you not in right direction using DataTable to map in and out to your Customer class. 可能您没有正确的方向使用DataTable映射到和映射到Customer类。 You are in a need of an ORM (Object relation mapper) now. 您现在需要一个ORM(对象关系映射器)。 There are certainly quite a few ORMs available for .NET community. .NET社区当然有很多ORM。

I am quite a big fan of Fluent NHibernate and even Entity Framework . 我是Fluent NHibernate甚至Entity Framework忠实Fluent NHibernate These always maps your database table rows to your list of objects. 这些总是将数据库表行映射到对象列表。

Probably these are known to you and if you are considering performance and using native data access for .NET. 这些可能是您已知的,并且如果您正在考虑性能并针对.NET使用本机数据访问。 I would then highly recommend you to go for Dapper and StackOverflow itself uses this ORM . 然后,我强烈建议您选择Dapper而StackOverflow本身使用此ORM I myself use Dapper when performance becomes an issue and need the comfort of development and clean looking codes. 当性能成为问题并且需要舒适的开发和简洁的代码时,我本人会使用Dapper。

For your instance, using Dapper would have a class Customer 对于您的实例,使用Dapper将有一个Customer

public class Customer {
    public Guid ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Gender { get; set; }
    public DateTime RegistrationDate { get; set; }
}

And your code to retrieve data from database to your customer object would be: 从数据库检索数据到客户对象的代码将是:

IEnumerable<Customer> allCustomers = _yourDapperConnection.Query<Customer>();

That's it! 而已! Look at the project's homepage for more details. 请查看项目的主页以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM