Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7444339
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T11:29:23+00:00 2026-05-29T11:29:23+00:00

I am trying to write a generic method that will convert a DataTable to

  • 0

I am trying to write a generic method that will convert a DataTable to a list of strongly typed objects.

The code that I’m working with so far is…

public List<T> ImportTable<T>(String fileName, String table)
{
    //Establish Connection to Access Database File
    var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");

    var tableData = new List<T>();

    foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
    {
        tableData.Add(ConvertRowToType<T>(row));
    }

    return tableData;
}

public T ConvertRowToType<T>(DataRow row)
{
    //??? What is the best thing to do here ???        
}

I’m not fixated on this code if anybody’s suggestions would require changes to it.

So let’s say I call this function passing in the type…

public class mdbConcern
{
    public Int32 ConcernId { get; set; }
    public String Concern { get; set; }
}

And the Data coming back in the DataTable looks like…

ConcernID  Concern
1          Law and Ethics
2          Mail
3          Business English
...        ...

What would be the best way to implement the ConvertRowToType(DataRow row) method?

Can someone show me how to use Func as one of the parameters so I can pass in some mapping information?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T11:29:24+00:00Added an answer on May 29, 2026 at 11:29 am

    I think an extension method is the best way to go:

    public static class Helper
    {
        public static T ToType<T>(this DataRow row) where T : new()
        {
            T obj = new T();
            var props = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor prop in props)
            {
                if(row.Table.Columns.IndexOf(prop.Name) >= 0 
                    && row[prop.Name].GetType() == prop.PropertyType)
                {   
                    prop.SetValue(obj, row[prop.Name]);
                }
            }
            return obj;
        }
    }
    

    Usage:

    public List<T> ImportTable<T>(String fileName, String table)
    {
        //Establish Connection to Access Database File
        var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");
    
        var tableData = new List<T>();
    
        foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
        {
            tableData.Add(row.ToType<T>());
        }
    
        return tableData;
    }
    

    Update I see that you asked for a Func that would provide the mapping. I’m not sure exactly what you envisioned but here is a method I came up with:

    public class mdbConcern
    {
        public Int32 ConcernId { get; set; }
        public String Concern { get; set; }
    
        public static PropertyDescriptor Mapping(string name)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(mdbConcern));
            switch (name)
            {
                case "Concern_Id":
                    return props.GetByName("ConcernId");
                case "Concern":
                    return props.GetByName("Concern");
                default:
                    return null;
            }
        }
    }
    
    public static class Helper
    {
        public static T ToType<T>(this DataRow row, Func<string, PropertyDescriptor> mapping) 
           where T : new()
        {
            T obj = new T();        
            foreach (DataColumn col in row.Table.Columns)
            {
                var prop = mapping(col.ColumnName);
                if(prop != null)
                    prop.SetValue(obj, row[col]);
            }
            return obj;
        }
    }
    

    Usage:

    foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
    {
        tableData.Add(row.ToType<mdbConcern>(mdbConcern.Mapping));
    }
    

    Here’s a version using attributes on the type’s properties to store its mapping. I think it’s a more natural solution:

    [AttributeUsage(AttributeTargets.Property)]
    public class ColumnMappingAttribute : Attribute
    {
        public string Name { get; set; }
        public ColumnMappingAttribute(string name)
        {
            Name = name;
        }
    }
    public class mdbConcern
    {
        ColumnMapping("Concern_Id")]
        public Int32 ConcernId { get; set; }
        ColumnMapping("Concern")]
        public String Concern { get; set; }
    }
    
    public static class Helper
    {   
        public static T ToType<T>(this DataRow row) where T : new()
        {
            T obj = new T();
            var props = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor prop in props)
            {
                var columnMapping = prop.Attributes.OfType<ColumnMappingAttribute>().FirstOrDefault();
    
                if(columnMapping != null)
                {
                    if(row.Table.Columns.IndexOf(columnMapping.Name) >= 0 
                        && row[columnMapping.Name].GetType() == prop.PropertyType)
                    {               
                        prop.SetValue(obj, row[columnMapping.Name]);
                    }
                }
            }
            return obj;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to write a generic Parse method that converts and returns a
I'm trying to write an extension method that will give me the MemberInfo representing
I'm trying to write a generic method that can be used to deserialize xml
I'm trying to write a generic interpolate method that works on any type that
I am trying to write a factory method that will create a derived instance
I am trying to write a generic repository that will perform basic methods on
Im trying to write a generic base class that will allow sub classes to
I'm trying to write a generic extension method that let's me do this: this.startDate
I'm trying to write a generic method to serialize an object that inherits from
I am trying to write a generic method that would allow me to pass

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.