【问题标题】:Converting DataTable to list将数据表转换为列表
【发布时间】:2012-04-07 11:24:27
【问题描述】:
    public static IList<Task> GetAllTasks()
    {
        return _taskSet.Task.ToList<Task>();
        // return sampleData.ToList();
    }

我正在将数据表转换为列表,但出现以下错误。如何将表格转换为列表。

Error   1   Instance argument: cannot convert from     orkTimeTable.Dataset.TaskSet.TaskDataTable' to 'System.Collections.Generic.IEnumerable<WorkTimeTable.Model.Task>'    c:\users\huzaifa.gain\documents\visual studio 2010\Projects\WorkTimeTable\WorkTimeTable\Model\TaskDataService.cs    24  20  WorkTimeTable

Error   2   'WorkTimeTable.Dataset.TaskSet.TaskDataTable' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments    c:\users\huzaifa.gain\documents\visual studio 2010\Projects\WorkTimeTable\WorkTimeTable\Model\TaskDataService.cs    24  20  WorkTimeTable

【问题讨论】:

    标签: c# .net ado.net


    【解决方案1】:

    总是有的:

    List<DataRow> list = dt.AsEnumerable().ToList();
    

    或者您可以针对特定情况使用动态或静态类型

    【讨论】:

      【解决方案2】:

      试试:

      public static IList<Task> GetAllTasks()
      {
          return _taskSet.Task.AsEnumerable().ToList();
      }
      

      【讨论】:

        【解决方案3】:

        这将从数据表中获取类似的字段并填充 T 类中的字段:

        public List<T> ToList<T>(this DataTable dt)
        {
            List<T> res = new List<T>();
            try {
                if (dt != null && dt.Rows.Count > 0) {
                    object prps = typeof(T).GetProperties;
                    object prpnames = prps.Select((System.Object f) => f.Name).ToList;
                    for (i = 0; i <= dt.Rows.Count - 1; i++) {
                        T Tinst = Activator.CreateInstance(typeof(T));
                        for (j = 0; j <= dt.Columns.Count - 1; j++) {
                            int prpInd = prpnames.IndexOf(dt.Columns(j).ColumnName);
                            if (prpInd >= 0) {
                                prps(prpInd).SetValue(Tinst, dt(i)(j), null);
                            }
                        }
                        res.Add(Tinst);
                    }
                }
            } catch (Exception ex) {
                PromptMsg(ex);
            }
            return res;
        }
        

        用法:如果我们有一个包含 FirstName、LastName、其他列...和

        的数据表
        public class classSample{
        
            private string _FirstName;
            public string FirstName{
                get {
                    return _FirstName;
                }
                set {
                    _FirstName = value;
                }
            }
        
            private string _LastName;
            public string LastName{
                get {
                    return _LastName;
                }
                set {
                    _LastName = value;
                }
            }
        
        }
        

        所以这将返回一个 classSample 列表:

        someDT.ToList<classSample>();
        

        【讨论】:

          【解决方案4】:
          public static IList<Task> GetAllTasks()
              {
                  List<Task> taskList = new List<Task>();
                  foreach (TaskSet.TaskRow r in _taskSet.Task.AsEnumerable())
                      taskList.Add(new WorkTimeTable.Model.Task()
                                       {
                                           Name = r.Name, Description = r.Description, ToDateTime = r.ToDate, FromDateTime = r.FromDate, TotalTime = r.TimeSpan
                                       });
                  return taskList;
              }
          

          【讨论】:

          • 这行得通。我将在接下来的 2 天内标记已回答的问题。
          【解决方案5】:

          使用以下类将数据表转换为列表。

          public static class Helper
          {
          
          
          
              public static List<T> DataTableToList<T>(this DataTable dataTable) where T : new()
              {
                  var dataList = new List<T>();
          
                  //Define what attributes to be read from the class
                  const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;
          
                  //Read Attribute Names and Types
                  var objFieldNames = typeof(T).GetProperties(flags).Cast<System.Reflection.PropertyInfo>().
                      Select(item => new
                      {
                          Name = item.Name,
                          Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
                      }).ToList();
          
                  //Read Datatable column names and types
                  var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
                      Select(item => new
                      {
                          Name = item.ColumnName,
                          Type = item.DataType
                      }).ToList();
          
                  foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
                  {
                      var classObj = new T();
          
                      foreach (var dtField in dtlFieldNames)
                      {
                          System.Reflection.PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);
          
                          var field = objFieldNames.Find(x => x.Name == dtField.Name);
          
                          if (field != null)
                          {
          
                              if (propertyInfos.PropertyType == typeof(DateTime))
                              {
                                  propertyInfos.SetValue
                                  (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                              }
                              else if (propertyInfos.PropertyType == typeof(Nullable<DateTime>))
                              {
                                  propertyInfos.SetValue
                                  (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                              }
                              else if (propertyInfos.PropertyType == typeof(int))
                              {
                                  propertyInfos.SetValue
                                  (classObj, ConvertToInt(dataRow[dtField.Name]), null);
                              }
                              else if (propertyInfos.PropertyType == typeof(long))
                              {
                                  propertyInfos.SetValue
                                  (classObj, ConvertToLong(dataRow[dtField.Name]), null);
                              }
                              else if (propertyInfos.PropertyType == typeof(decimal))
                              {
                                  propertyInfos.SetValue
                                  (classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
                              }
                              else if (propertyInfos.PropertyType == typeof(String))
                              {
                                  if (dataRow[dtField.Name].GetType() == typeof(DateTime))
                                  {
                                      propertyInfos.SetValue
                                      (classObj, ConvertToDateString(dataRow[dtField.Name]), null);
                                  }
                                  else
                                  {
                                      propertyInfos.SetValue
                                      (classObj, ConvertToString(dataRow[dtField.Name]), null);
                                  }
                              }
                              else
                              {
          
                                  propertyInfos.SetValue
                                      (classObj, Convert.ChangeType(dataRow[dtField.Name], propertyInfos.PropertyType), null);
          
                              }
                          }
                      }
                      dataList.Add(classObj);
                  }
                  return dataList;
              }
          
              private static string ConvertToDateString(object date)
              {
                  if (date == null)
                      return string.Empty;
          
                  return date == null ? string.Empty : Convert.ToDateTime(date).ConvertDate();
              }
          
              private static string ConvertToString(object value)
              {
                  return Convert.ToString(ReturnEmptyIfNull(value));
              }
          
              private static int ConvertToInt(object value)
              {
                  return Convert.ToInt32(ReturnZeroIfNull(value));
              }
          
              private static long ConvertToLong(object value)
              {
                  return Convert.ToInt64(ReturnZeroIfNull(value));
              }
          
              private static decimal ConvertToDecimal(object value)
              {
                  return Convert.ToDecimal(ReturnZeroIfNull(value));
              }
          
              private static DateTime convertToDateTime(object date)
              {
                  return Convert.ToDateTime(ReturnDateTimeMinIfNull(date));
              }
          
              public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
              {
                  if (datetTime != DateTime.MinValue)
                  {
                      if (excludeHoursAndMinutes)
                          return datetTime.ToString("yyyy-MM-dd");
                      return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
                  }
                  return null;
              }
              public static object ReturnEmptyIfNull(this object value)
              {
                  if (value == DBNull.Value)
                      return string.Empty;
                  if (value == null)
                      return string.Empty;
                  return value;
              }
              public static object ReturnZeroIfNull(this object value)
              {
                  if (value == DBNull.Value)
                      return 0;
                  if (value == null)
                      return 0;
                  return value;
              }
              public static object ReturnDateTimeMinIfNull(this object value)
              {
                  if (value == DBNull.Value)
                      return DateTime.MinValue;
                  if (value == null)
                      return DateTime.MinValue;
                  return value;
              }
          }
          

          您可以将数据表转换为列表

          var mytbl=dt.DataTableToList();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-04-17
            相关资源
            最近更新 更多