将DataTable转换为我的列表<t>

时间:2017-05-19 07:26:59

标签: c# sqlite xamarin

            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
            SqliteDataReader rdr = cmd.ExecuteReader();
            dt.Load(rdr);
            return dt;

DataTable tb = new DataTable();List<Details> objList = new List<Details>

            foreach (var obj in dt)
            {
                var item = new Details();
                item.ID = obj.ID;
                item.Dosage = obj.Dosage;
                item.Drug = obj.Drug;
                item.Patient = obj.Patient;
                item.Date = obj.Date;

                results.Add(item);
            }

这个想法在这里但是在forceach中的 dt 中存在错误(在dt中的var obj)

1 个答案:

答案 0 :(得分:0)

你必须

  1. 执行读者
  2. 阅读游标
  3. 创建班级实例
  4. 将这些实例收集到List<T>
  5. 像这样的东西

       // List which will be used to collect records from the query
       List<MyClass> list = new List<MyClass>();
    
       ...
       cmd.CommandText = sql;
    
       //DONE: execute reader; wrap IDisposable into using
       using (SqliteDataReader rdr = cmd.ExecuteReader()) {
         //DONE: read each cursor's record
         while (rdr.Read()) {
           //DONE: Turn each record into MyClass instance
           MyClass item = new MyClass();
    
           //TODO: Assign properties
           item.Property1 = Convert.ToString(rdr[0]);
           item.Property2 = Convert.ToInt32(rdr[1]); 
           ...  
    
           //DONE: Finally, collect all the intances created into the list 
           list.Add(item);
         }      
       } 
       ...