【问题标题】:selecting a certain column value from looping in ienumerable从可枚举的循环中选择某个列值
【发布时间】:2013-07-30 21:33:12
【问题描述】:

我有一个存储过程的 IEnumerable 结果,我正在循环遍历结果以获取列 (GUID) 的值。我不确定如何从 foreach 循环中的结果集中获取 Guid 列

这就是我所拥有的:

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();
            }
        }

【问题讨论】:

  • @CamBruce 如何从 foreach 循环中的结果中获取 Guid 列
  • 这会让你指向正确的方向:msdn.microsoft.com/en-us/library/…
  • @CamBruce 不确定这是否与我正在寻找的类型相同。
  • @GrantWinney 返回包含 3 列、id、level 和 guid 的存储过程中的行 - 我有兴趣获取 guid 列中的值。
  • @GrantWinney 它们是 DbDataRecord 对象,但它是非泛型 IEnumerable,因此它也可能是 IEnumerable,因为对于基本的非-通用 IEnumerable。实际上,情况更糟,因为您至少可以转换 IEnumerable

标签: c# ienumerable


【解决方案1】:

您不能直接在非泛型 IEnumerable 上使用大多数普通的 linq 扩展方法...但您可以调用 .Cast<T>() 使其成为 IEnumerable<T>。到那时,事情就变得容易了:

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"]);
    }
} 

【讨论】:

  • Item 来自哪里?我让它抛出不包含定义的编译错误。
  • 我的错误,现在修正。 C# 将其用作索引器。我刚刚在VB中回答了一个类似的问题,VB使用.Item("")
【解决方案2】:

您需要自己从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"]);
                      }
                    }
                }
            }

【讨论】:

  • 这会将整个结果集强制放入 RAM,而不是像 DataReader 所期望的那样一次迭代一个结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多