Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
DataSet values to store in List object
I have a DataSet, that needs to be passed into a list object. Name of columns in DataSet are same as properties of list object.

Example:

Data Set columns

C#
PickupCity
 PickupState
 PickupCountry

List Object Properties

C#
ContactPerson
 PickupCity
 PickupState
 PickupCountry
 PhoneNumber

I do not want to assign / define each column one by one, like:

C#
PickupCity = dr["PickupCity"].ToString(),

I am looking for something like below that automatically assign available data with same column / property name:

C#
List<PickupClass> pickup = DataSet


What I have tried:

C#
if (dataSet != null)
{
    dataTable = dataSet.Tables[0];

    _inboundDataTable = (from DataRow dr in dataTable.Rows
                         select new InboundDataTable()
                         {
                             OriginCompany = dr["OriginCompany"].ToString(),
                             OriginAddress = dr["OriginAddress"].ToString(),
                             OriginAddress2 = dr["OriginAddress2"].ToString(),


This is the part of code, which is currently implemented. Want to change it to more robust one.
Posted
Updated 4-Dec-21 10:11am
Comments
[no name] 4-Dec-21 13:13pm    
Seems redundant. Just use the data table.

 
Share this answer
 
Hi,
After searching and few adjustments, below solution worked for me.

Create helper class
C#
public static class Helper
 {
     public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
     {
         try
         {
             List<T> list = new List<T>();

             foreach (var row in table.AsEnumerable())
             {
                 T obj = new T();

                 foreach (var prop in obj.GetType().GetProperties())
                 {
                     try
                     {
                         PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                         propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                     }
                     catch
                     {
                         continue;
                     }
                 }

                 list.Add(obj);
             }

             return list;
         }
         catch
         {
             return null;
         }
     }
 }

Called helper using
C#
dataTable = dataSet.Tables[0];
List<InboundDataTable> _inboundDataTable = dataTable.DataTableToList<InboundDataTable>(); 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900