如何从表格中选择项目到列表<t>?</t>

时间:2014-04-01 12:25:47

标签: c# asp.net sql

如何将数据阅读器的结果转换为List<String>

到目前为止,这是我的代码:

public List<string> Item_Getall()
{
    List<string> data = new List<string>();
    SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
    cmd.CommandType = CommandType.StoredProcedure;
    oo.conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
        data.Add(rdr["item_name_id_pk"].ToString());
        data.Add(rdr["item_name_arabic"].ToString());
        data.Add(rdr["item_componant"].ToString());
        data.Add(rdr["item_componant_arabic"].ToString());
        data.Add(rdr["item_price"].ToString());
        data.Add(rdr["item_image"].ToString());
        data.Add(rdr["item_category_name_id_fk"].ToString());
    }
    oo.conn.Close();
    return data;
}

3 个答案:

答案 0 :(得分:2)

您最好使用自定义类型列表而不是字符串,并将自定义类型对象存储在列表

List<YourCustomType> data = new List<YourCustomType>();

自定义类型

public class YourCustom
{
     public string ItemName {get; set;}
     //Similarly all the properties.
}

从数据读取器读取值并添加自定义类型列表

while (rdr.Read())
{
    data.Add(new YourCustom()
    {
       Id = rdr["item_name_id_pk"].ToString(),
       Name = rdr["item_name_arabic"].ToString()
       //Similarly all other properties could be set 
    }
}

答案 1 :(得分:1)

我想你会想要创建一个自定义类并返回这个类的列表:

public class Item
{
     public int Id { get; set; }
     public string Name { get; set; }
}

阅读将如下:

var data = new List<Item>();
while (rdr.Read())
{
    data.Add(new Item()
    {
        Id = int.Parse(rdr["item_name_id_pk"]),
        Name = rdr["item_name_arabic"].ToString()
    }
}
return data;

另外,查看using()语句,这将使您的代码在数据库调用期间的异常情况下更加健壮。

答案 2 :(得分:0)

使用DataAdapter和自定义类型:

SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
cmd.CommandType = CommandType.StoredProcedure;
oo.conn.Open();

var adapter = new SqlDataAdapter(cmd);

DataTable dt;
adapter.Fill(dt);

oo.Close()

//Convert DataTable to a list of YourType
List<YourType> data = dt.AsEnumerable().Select(s=> 
                         new YourType { 
                          item_name_id_pk = s.Field<FieldDataType>("item_name_id_pk"),
                          item_name_arabic = s.Field<FieldDataType>("item_name_arabic"),
                             ...
                         })
                         .ToList();

您的自定义类型就像;

public class YourType
{
    //Replace the DataType with correct datatype to match with FieldDataType
    public DataType item_name_id_pk {get; set;}
    public DataType item_name_arabic {get; set;}
    ...
}