Convert DataSet to List

后端 未结 11 2180
一整个雨季
一整个雨季 2020-12-04 08:39

Here is my c# code

Employee objEmp = new Employee();
List empList = new List();
foreach (DataRow dr in ds.Tables[0].Rows)
{
          


        
相关标签:
11条回答
  • 2020-12-04 08:56

    Here's extension method to convert DataTable to object list:

        public static class Extensions
        {
            public static List<T> ToList<T>(this DataTable table) where T : new()
            {
                IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
                List<T> result = new List<T>();
    
                foreach (var row in table.Rows)
                {
                    var item = CreateItemFromRow<T>((DataRow)row, properties);
                    result.Add(item);
                }
    
                return result;
            }
    
            private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
            {
                T item = new T();
                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(System.DayOfWeek))
                    {
                        DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                        property.SetValue(item,day,null);
                    }
                    else
                    {
                        if(row[property.Name] == DBNull.Value)
                            property.SetValue(item, null, null);
                        else 
                            property.SetValue(item, row[property.Name], null); 
                    }
                }
                return item;
            }
        }
    

    usage:

    List<Employee> lst = ds.Tables[0].ToList<Employee>();
    

    @itay.b CODE EXPLAINED: We first read all the property names from the class T using reflection
    then we iterate through all the rows in datatable and create new object of T,
    then we set the properties of the newly created object using reflection.

    The property values are picked from the row's matching column cell.

    PS: class property name and table column names must be same

    0 讨论(0)
  • 2020-12-04 08:59

    Try something like this:

    var empList = ds.Tables[0].AsEnumerable()
        .Select(dataRow => new Employee
        {
            Name = dataRow.Field<string>("Name")
        }).ToList();
    
    0 讨论(0)
  • 2020-12-04 09:01

    Try the above which will run with any list type.

      public DataTable ListToDataTable<T>(IList<T> data)
        {
            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, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    
    0 讨论(0)
  • 2020-12-04 09:04

    Fill the dataset with data from, say a stored proc command

    DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter();
    adapter.SelectCommand = cmd;
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    

    Get The Schema,

    string s = ds.GetXmlSchema();
    

    save it to a file say: datasetSchema.xsd. Generate the C# classes for the Schema: (at the VS Command Prompt)

    xsd datasetSchema.xsd /c
    

    Now, when you need to convert the DataSet data to classes you can deserialize (the default name given to the generated root class is NewDataSet):

    public static T Create<T>(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (StringReader reader = new StringReader(xml))
        {
            T t = (T)serializer.Deserialize(reader);
    
            reader.Close();
            return t;
        }
    }
    
    var xml = ds.GetXml();
    var dataSetObjects = Create<NewDataSet>(xml);
    
    0 讨论(0)
  • 2020-12-04 09:13

    Add a new class named as "Helper" and change the property of the class to "public static"

    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;
            }
        }
    }
    

    and access this class in your code behind as like below

     DataTable dtt = dsCallList.Tables[0];
     List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>();
    
    0 讨论(0)
  • 2020-12-04 09:16
                    DataSet ds = new DataSet();
                    ds = obj.getXmlData();// get the multiple table in dataset.
    
                    Employee objEmp = new Employee ();// create the object of class Employee 
                    List<Employee > empList = new List<Employee >();
                    int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset
                    for (int i = 1; i < table; i++)// set the table value in list one by one
                    {
                        foreach (DataRow dr in ds.Tables[i].Rows)
                        {
                            empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) });
                        }
                    }
                    dataGridView1.DataSource = empList;
    

    enter image description here

    0 讨论(0)
提交回复
热议问题