面对将列表转换为数据表c#的问题

时间:2014-04-26 07:11:37

标签: c#

我有以下代码,并面临将列表转换为数据表的问题。 这一行给出了错误。 DataTable studentTable =学生;

public DataTable GetDetails()
        {

            List<Student> Students = new List<Student>(){
                new Student() { Name = "Jack", Age = 1, StudentId = 100 },
                new Student() { Name = "Smith", Age = 2, StudentId = 101 },   
                       new Student() { Name = "Smit", Age = 3, StudentId = 102 },};
            DataTable studentTable = Students;// This line gives error.
        }

        public class Student
        {
            public string Name;
            public int Age;
            public int StudentId;
        }

请纠正我。

2 个答案:

答案 0 :(得分:0)

请试试这个。你必须先转换它。 C#不允许您为彼此分配不同类型的值。

 public DataTable GetDetails()
    {

        List<Student> Students = new List<Student>(){
            new Student() { Name = "Jack", Age = 1, StudentId = 100 },
            new Student() { Name = "Smith", Age = 2, StudentId = 101 },   
                   new Student() { Name = "Smit", Age = 3, StudentId = 102 },};
        DataTable studentTable = new DataTable();// Changed
       using(var reader = ObjectReader.Create(Students)) 
          {
            studentTable.Load(reader);
          }
       return studentTable; //need it?
    }

对不起,如果它不起作用,请查看更多Here

答案 1 :(得分:0)

您应该创建列,然后添加行,而不是制作列表。

Studenttable.columns.add("Name", typeof(string));
Studenttable.columns.add("Agg", typeof(int));
Studenttable.columns.add("StudentID", typeof(int));

Studenttable.Rows.add("Jack",1,100);