Update DataTable row without using Loop statements

Sometime we need to update a single row in a DataTable based on certain criteria. In those situations, we generally use a loop statement to find that record in the DataTable and updates the columns in that row.
LINQ Provides an easy way for this type of cases.We can get the row in the DataTable which matches the criteria by using simple LINQ Query. The changes made in the returned DataRow will effect the DataTable values.
Example: I have the following DataTable

ID          Name       Country
----      ----------   --------
1           Ram           India
2           Martin        USA
3           Raj             India
4           Prem          Australia

Now I  want to Update the 'Country' value to "USA" if ID=3, then it can be done in the following ways

//using Loop
for (int i = 0; i < oDt.Rows.Count; i++)
  {
      if (oDt.Rows[i]["ID"].ToString() == "3")
      {
         oDt.Rows[i]["Country"] = "USA";
         break;
       }
   }


//Without using Loop --using LINQ
DataRow oDr = oDt.AsEnumerable().Where(r => ((string)r["ID"]).Equals("3") ).First();
oDr["Country"] = "USA";

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment