Convert DataSet to List

后端 未结 11 2213
一整个雨季
一整个雨季 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 09:18

    I couldn't get Nitin Sawant's answer to work, but I was able to modify his code to work for me. Essentially I needed to use GetRuntimeFields instead of GetProperties. Here's what I ended up with:

    public static class Extensions
    {
        public static List ToList(this DataTable table) where T : new()
        {
            IList fields = typeof(T).GetRuntimeFields().ToList();
            List result = new List();
            if (row.Table.Columns.Contains(field.Name))
            {
                foreach (var row in table.Rows)
                {
                    var item = CreateItemFromRow((DataRow)row, fields);
                    result.Add(item);
                }
            }
    
            return result;
        }
    
        private static T CreateItemFromRow(DataRow row, IList fields) where T : new()
        {
            T item = new T();
    
            foreach (var field in fields)
            {
                if (row[field.Name] == DBNull.Value)
                    field.SetValue(item, null);
                else
                    field.SetValue(item, row[field.Name]);
            }
            return item;
        }
    }
    

提交回复
热议问题