【问题标题】:Get Values from DataTable by row and column name通过行和列名从 DataTable 中获取值
【发布时间】:2014-12-15 18:09:15
【问题描述】:

我通常习惯于SQL 中的传统表格,其中我有多个columns 并填充了行。我执行一个存储过程并将所有数据存储在DataTable 中并循环遍历表以获得我需要的结果。例如,

 public static DataTable getInfo (string sessionID)
    {
        try
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SandBox"].ConnectionString);
            SqlCommand cmd = new SqlCommand("GetSessionInfo", conn);
            cmd.Parameters.AddWithValue("SessionGUID", sessionID);
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            return dt;
        }
        catch (Exception)
        {

            throw;
        }
    }

我会加载数据表:

 DataTable infoTbl = new DataTable();
 infoTbl = getInfo(lbldatabasesessionID.Text);

我会使用foreach 循环来遍历数据表。

foreach (DataRow row in infoTbl.Rows)
{
   string x = col.ToString();
}

我遇到的问题是数据库人给了我一个返回不同输出的存储过程(与我习惯的不同)。它是基于行的。

例如,我可以访问First Name 的唯一方法是,如果我对以下位置进行硬编码:

string firstName = infoTbl.Rows[16][2].ToString();

我不喜欢这样做,因为位置可能会发生变化。我如何通过知道ElementTypeElementName 的名称来访问ElementValue

有什么建议吗?

【问题讨论】:

    标签: c# asp.net sql-server-2008 stored-procedures datatable


    【解决方案1】:

    使用数据集:

            string firstName = string.Empty;
    
            DataRow row = table.Select("ElementType = 'Demographics' AND ElementName = 'FirstName'").FirstOrDefault();
    
            if (row != null)
            {
                firstName = (string)row["ElementValue"];
            }
    

    使用 Linq:

            string firstName = table.AsEnumerable()
                .Where(f => f.Field<string>("ElementType") == "Demographics" && 
                    f.Field<string>("ElementName") == "FirstName")
                .Select(f => f.Field<string>("ElementValue")).FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-07
      • 2012-09-05
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多