Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何传递数据,为数组选择_C#_Arrays - Fatal编程技术网

C# 如何传递数据,为数组选择

C# 如何传递数据,为数组选择,c#,arrays,C#,Arrays,如何将下面的选择数据保存到数组中 SqlConnection conConexao1 = clsdb.AbreBanco(); SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1); SqlDataReader dr1 = cmd1.ExecuteReader(); if (dr1.HasRows == true) { if (dr1.Read())

如何将下面的选择数据保存到数组中

SqlConnection conConexao1 = clsdb.AbreBanco();
SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
SqlDataReader dr1 = cmd1.ExecuteReader();

if (dr1.HasRows == true)
{
    if (dr1.Read())
    {
        id = int.Parse(dr1[0].ToString());
        templete1  = (dr1[1].ToString());
        templete2 = (dr1[2].ToString());
    }
}

我已经尝试使用foreach,但总是传递最后一个表数据。

作为一个集合,
List
提供了比数组更好的灵活性。
集合应该在循环外部创建,元素应该添加到循环内部

List<Usuarios> list = new List<Usuarios>();
using (SqlConnection conConexao1 = clsdb.AbreBanco())
using (SqlCommand cmd1 = new SqlCommand(
    "select id, tamplete1, tamplete2 from usuarios ", conConexao1))
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
    while (dr1.Read())
    {
        list.Add(new Usuarios
        {
            Id = dr1.GetInt32(0),
            Templete1 = dr1[1].ToString(),
            Templete2 = dr1[2].ToString()
        });
    }
}
如果由于某种原因,您必须使用数组作为集合

Usuarios[]array=list.ToArray()

使用
while(dr1.read())
而不是
if(dr1.read())
将数组放在while中?我看不到任何数组此处数组代码没有传递,因为问题就在于此。您可以使用
语句链接
以避免答案中出现某些嵌套级别。
public class Usuarios
{
    public int Id { get; set; }
    public string Templete1 { get; set; }
    public string Templete2 { get; set; }
}