从数据集c#填充数组

时间:2014-04-30 13:53:11

标签: c# asp.net arrays dataset sqlclient

我有一个包含6个字符串的数据集。如何使用数据集中的这些字符串填充字符串数组。我想象一下循环数据集 我有一个有问题和答案的测验课。

下面是填充数据集的代码。

            SqlConnection connect = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand();
            command.Connection = connect;
            command.CommandType = CommandType.Text;
            command.CommandText = "Select * from Questions";

            SqlDataAdapter dataapt = new SqlDataAdapter(command);
            DataSet questions = new DataSet();

            try
            {
                connect.Open();
                dataapt.Fill(questions, "Questions");
            }

继承我的测验课

           public class Quiz
            {
              public string[] questions { get; set; }
              public string[] answers { get; set; }



    public Quiz()
    {
        questions = new string[] { "First", "Second", "Third", "Fourth","Fifth","sixth" };
        answers = new string[] { "First", "Second", "Third", "Fourth", "Fifth", "sixth" };
    }

是否可以从数据集中填充数组?

1 个答案:

答案 0 :(得分:0)

是。可以办到。看一下这个例子。

DataTable dt = new DataTable();
dt.Columns.Add("Questions");

dt.Rows.Add(new String[] { "One" });
dt.Rows.Add(new String[] { "Two" });
dt.Rows.Add(new String[] { "Three" });
dt.Rows.Add(new String[] { "Four" });
dt.Rows.Add(new String[] { "Five" });

String[] questions = dt.AsEnumerable().Select(x => x["Questions"].ToString()).ToArray();