Update two columns in a DataTable using LINQ

I want to update two DataTable columns on the same row using LINQ query. I am currently using the following two lines to do the same:

oldSP.Select(string.Format("[itemGuid] = '{0}'", itemGuid)).ToList<DataRow>().ForEach(r => r["startdate"] = stDate); oldSP.Select(string.Format("[itemGuid] = '{0}'", itemGuid)).ToList<DataRow>().ForEach(r => r["enddate"] = enDate); 

How to do this on one line using one Select ?

+6
source share
4 answers

You can do this in one line, just pass the appropriate action delegate to the ForEach method:

 oldSP.Select(string.Format("[itemGuid] = '{0}'", itemGuid)) .ToList<DataRow>() .ForEach(r => { r["startdate"] = stDate; r["enddate"] = enDate; }); 

You can also use LINQ to DataSet (looks more readable to me than single-line):

 var rowsToUpdate = oldSP.AsEnumerable().Where(r => r.Field<string>("itemGuid") == itemGuid); foreach(var row in rowsToUpdate) { row.SetField("startdate", stDate); row.SetField("enddate", enDate); } 
+25
source

Try the following:

 oldSP.Select(string.Format("[itemGuid] = '{0}'", itemGuid)).ToList<DataRow>() .ForEach(r => { r["startdate"] = stDate; r["enddate"] = enDate; }); 
+1
source

Use curly braces to perform two operations:

 oldSP.Select(string.Format("[itemGuid] = '{0}'", itemGuid)) .ToList<DataRow>() .ForEach(r => { r["enddate"] = enDate); r["startdate"] = stDate; }); 

But to read the code, I would use the old-fashioned foreach .

+1
source

I did not like any of the examples that I saw on the Internet, so here is my example

  DataTable dt = new DataTable(); dt.Columns.Add("Year"); dt.Columns.Add("Month"); dt.Columns.Add("Views"); for (int year = 2011; year < 2015; year++) { for (int month = 1; month < 13; month++) { DataRow newRow = dt.NewRow(); newRow[0] = year; newRow[1] = month; newRow[2] = 0; dt.Rows.Add(newRow); } } dataGridView1.DataSource = dt; //if using Lambda //var test = dt.AsEnumerable().Where(x => x.Field<string>("Year") == "2013" && x.Field<string>("Month") == "2").ToList(); var test = (from x in dt.AsEnumerable() where x.Field<string>("Year") == "2013" where x.Field<string>("Month") == "2" select x).ToList(); test[0][0] = "2015"; dt.AcceptChanges(); 

// if the sql entry uses dt.SubmitChanges () instead

-1
source

Source: https://habr.com/ru/post/957660/


All Articles