将列表放入c#中的数据表列

时间:2015-07-05 16:14:16

标签: c# datatable

我正在尝试在一个datatable列中显示两个不同列的值。是否可以将它们添加到List并将List放入datatable列?

 DataTable dt = new DataTable();

              dt.Columns.Add("FullName");
              dt.Columns.Add("StudentId");

              foreach (var studentSubject in studentSubjects)
              {
                  dt.Columns.Add(studentSubject.ToString());
              }

              foreach (var g in groups)
              {
                  DataRow dr = dt.NewRow();
                  dr["FullName"] = g.FullName;
                  dr["StudentId"] = g.StudentId;

                  foreach (var sc in g.ExamScore)
                  {

                      List<SubjectProperty> listSubjectProperty = new List<SubjectProperty>();

                      listSubjectProperty.Add(new SubjectProperty
                      {
                          SubjectId = sc.SubjectId,
                          Score = sc.ExamScore
                      });

                      dr[sc.SubjectName] = listSubjectProperty;
                  }

                  dt.Rows.Add(dr);

1 个答案:

答案 0 :(得分:0)

试试这个

using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("A List Object", typeof(List<string>));

            List<string> names = null;

            names = new List<string>(new string[] {"John", "Mary"});
            dt.Rows.Add(names);

            names = new List<string>(new string[] { "Bob", "Carol", "Ted", "Alice" });
            dt.Rows.Add(names);

            names = new List<string>(new string[] { "Harry", "Sally"});
            dt.Rows.Add(names);
        }
    }
}
​