c# - 按行和列名称从 DataTable 中获取值

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

我通常习惯于 SQL 中的传统表,其中有多个填充了行的。我执行一个存储过程并将所有数据存储在 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 循环来循环访问 DataTable。

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

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

enter image description here

我可以访问例如名字的唯一方法是对位置进行硬编码,例如:

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

我觉得这样做不太舒服,因为职位可能会发生变化。如何通过知道 ElementTypeElementName 的名称来访问 ElementValue

有什么建议吗?

最佳答案

使用数据集:

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

关于c# - 按行和列名称从 DataTable 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490334/

相关文章:

c# - 使用 Ninject 跨类传递参数

c# - 在 C# 和 DateTime 中嵌入 IronRuby

javascript - 如何使用 jquery 或 javascript 获取 tabcontainer ID?

SQL 内部联接无法获取前一日期的更改

c# - 使用 onServerClick 获取 href 值

asp.net - Owin 自主机 api 抛出异常 : The format of the specified network name is invalid

c# - Sharepoint 访问请求 "Permission"代码

c# - SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为 : 5. 5.1 需要身份验证。

sql-server - 如何强制文件流垃圾收集器以最高优先级完成其工作?

c# - TreeMap 的旅行商问题(无汉密尔顿路径)