我通常习惯于 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();
}
我遇到的问题是数据库人员给了我一个返回不同输出的存储过程(与我习惯的不同)。它是基于行的。
我可以访问例如名字
的唯一方法是对位置进行硬编码,例如:
string firstName = infoTbl.Rows[16][2].ToString();
我觉得这样做不太舒服,因为职位可能会发生变化。如何通过知道 ElementType
和 ElementName
的名称来访问 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/