c# - 从 SqlDataReader 填充通用列表 [英] c# - Fill generic list from SqlDataReader

查看:38
本文介绍了c# - 从 SqlDataReader 填充通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 SqlDataReader 返回的值添加到通用列表?我有一种方法,我使用 SqlDataReaderCategory 表中获取 CategoryID .我想添加所有 CategoryID 一个通用列表.

How can I add values that a SqlDataReader returns to a generic List? I have a method where I use SqlDataReader to get CategoryID from a Category table. I would like to add all the CategoryID a generic List.

这不起作用,因为它只返回一个 categoryID 而这是最后一个.我想将所有 categoryID 添加到列表中,然后返回它们.

This dose not work because it returns only one categoryID and that is the last one. I want to add all the categoryID to the list and then return them.

我该怎么做?

SqlConnection connection = null;
SqlDataReader reader = null;
SqlCommand cmd = null;

try
{
    connection = new SqlConnection(connectionString);
    cmd = new SqlCommand("select CategoryID from Categories", connection );

    connection.Open();

    List<int> catID = new List<int>();
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
    }
}
finally
{
    if (connection  != null)
        connection.Close();
}
return catID;

推荐答案

试试这个,更好,更安全,使用延迟加载,更少的代码,工作,...:

Try like this, it's better, safer, uses lazy loading, less code, working, ...:

public IEnumerable<int> GetIds()
{
    using (var connection = new SqlConnection(connectionString))
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "select CategoryID from Categories";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader.GetInt32(reader.GetOrdinal("CategoryID"));
            }
        }
    }
}

然后:

List<int> catIds = GetIds().ToList();

这篇关于c# - 从 SqlDataReader 填充通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆