简体   繁体   中英

What is the fastest way to fill a simple object from a DataTable?

I was just wondering is there a faster or more efficient method to convert a DataTable to an object?

The method I am currently using is this:

public class Job {
    int JobID { get; set; }
    decimal JobCost { get; set; }

    Job(DataRow dr)
    {
        ID = Convert.ToInt32(dr["ID"]);
        if(dr["JobCost "] != DBNull.Value)
            JobCost = Convert.ToDecimal(dr["DelAmt"]);
    }
}

public static List<Job> FillObjects()
{
    DataTable dtJobs = JobController.GetJobTable();

    foreach (DataRow dr in dtJobs.Rows)
    {
        jobs.Add(new Job(dr));          
    }

    return jobs
}

This is an obviously simplified example, however this gets rather slow with many rows in the data table and many properties in the object. Is there a faster or more efficient method for doing something like this?

Thanks in advance for any replies!

Without utilizing Entity Framework your options are limited to something like you've already developed or using Linq to put them into their objects such as:

dtJobs.AsEnumerable().Select(x=> new Job{
                                   ID = x.Field<int>("ID"),
                                   JobCost = x.Field<Decimal>("DelAmt")
});

This will return an enumerable of Job objects, that you can then use to do whatever. One caveat with your current set up is that this will not allow for nulls to be returned. If you wanted to do this use a nullable decimal field and handle the null else where.

If order is not important - you can do this using a parallel for each loop over the data rows. This will be much faster to process. One must be careful doing this on a server application though.

Note: I updated to lock on the list when adding to it. You can also use a collection from the concurrent collections instead of using a lock.

  class Program
{
    static void Main(string[] args)
    {
        var sync = new Object();
        var dt = new DataTable();  // fill data
        var jobs = new List<Job>();
        Parallel.ForEach(dt.AsEnumerable(), row =>
        {
            var job = JobFactory.GetJob(row);
            lock (sync)
            {
                jobs.Add(job);
            }
        });
    }
}

public class JobFactory
{
    public static Job GetJob(DataRow d)
    {
        var j = new Job();

        // do processing here from data row to fill job object
        return j;
    }
}

public class Job
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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