Get Values from DataTable by row and column name

14,680

Using DataSet:

        string firstName = string.Empty;

        DataRow row = table.Select("ElementType = 'Demographics' AND ElementName = 'FirstName'").FirstOrDefault();

        if (row != null)
        {
            firstName = (string)row["ElementValue"];
        }

Using Linq:

        string firstName = table.AsEnumerable()
            .Where(f => f.Field<string>("ElementType") == "Demographics" && 
                f.Field<string>("ElementName") == "FirstName")
            .Select(f => f.Field<string>("ElementValue")).FirstOrDefault();
Share:
14,680
smr5
Author by

smr5

Software developer.

Updated on June 04, 2022

Comments

  • smr5
    smr5 almost 2 years

    I'm typically used to traditional table in SQL where I have multiple columns with rows populated. I execute a stored procedure and store all the data in DataTable and loop through the table to get the results I need. For example,

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

    I would load the DataTable:

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

    And I would use foreach loop to loop through the DataTable.

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

    The issue I run into is the database guy gave me a stored procedure that returns a different output (different from what I'm used to). It's a row based.

    enter image description here

    The only way I can access for example the First Name is if I hard code the position like:

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

    I don't feel comfortable doing this since the position could potentially change. How would I access ElementValue by knowing the name knowing ElementType and ElementName?

    Any suggestions?