selecting a certain column value from looping in ienumerable

我的梦境 提交于 2019-12-12 01:24:56

问题


I have a result of IEnumerable from a stored procedure and i am looping through the results inorder to get the value of a column(GUID). I am unsure of how to go about on getting the Guid column from my results set in the foreach loop

this is what i have:

var results = GetGuids(instId);
foreach (var item in results)
{

}

public IEnumerable GetGuids(int id)
        {
            using (SqlCommand _command = new SqlCommand("StoredProc"))
            {
                _command.Connection = new SqlConnection(conString);
                _command.Connection.Open();
                _command.CommandType = CommandType.StoredProcedure;
                _command.Parameters.AddWithValue("@ItemID", id);

                return _command.ExecuteReader();
            }
        }

回答1:


You can't use most of the normal linq extension methods directly on the non-generic IEnumerable... but you can call .Cast<T>() to make it an IEnumerable<T>. At that point, things get easier:

public IEnumerable<Guid> GetGuids(int id)
{
    using (SqlCommand _command = new SqlCommand("StoredProc"))
    {
        _command.Connection = new SqlConnection(conString);
        _command.Connection.Open();
        _command.CommandType = CommandType.StoredProcedure;
        _command.Parameters.Add("@ItemID", SqlDbType.Int).Value =  id;

            return _command.ExecuteReader()
                  .Cast<DbDataRecord>()
                  .Select(r => (Guid)r["GuidColumn"]);
    }
} 



回答2:


You need to produce the results yourself from the SqlDataReader

 var results = GetGuids(instId);
    foreach (var item in results)
    {

    }

    public IEnumerable<Guid> GetGuids(int id)
            {
                using (SqlCommand _command = new SqlCommand("StoredProc"))
                {
                    _command.Connection = new SqlConnection(conString);
                    _command.Connection.Open();
                    _command.CommandType = CommandType.StoredProcedure;
                    _command.Parameters.AddWithValue("@ItemID", id);

    var guids = new List<Guid>();

                   using (SqlDataReader reader = _command.ExecuteReader())
                   {
                     while (reader.Read()
                     {
                    guids.Add( (Guid)reader["GuidColumn"]);
                      }
                    }
                }
            }


来源:https://stackoverflow.com/questions/17957832/selecting-a-certain-column-value-from-looping-in-ienumerable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!