Add column to current DataTable using linq

Is it possible to add a new column that is calculated by a column in an existing DataTable

dt1.Rows.Add(new string[] { "1", "a", "a1" }); dt1 = (from r in dt1.AsEnumerable() select new { col3 = r.Field<string>("col1") + r.Field<string>("col2") }); 

as a result, the DataTable must contain a new column

+4
source share
2 answers

Yes, but not through LINQ:

 DataColumn col3 = new DataColumn(); col3.DataType = typeof(decimal); // or something suitable col3.ColumnName = "sum"; col3.Expression = "col1 + col2"; dt1.Columns.Add(col3); 

You can also use the LINQ approach to create a projection, but this does not change the table (therefore, assigning dt1 is an error). Technically, you can write an expression parser to write .Expression for you, but I don’t see it to be a good investment of time.

+2
source

Here is an alternative solution to shorten the For / ForEach cycle,

  dt1.Columns.Add("sum", typeof(System.Decimal)); dt1.Columns["sum"].Expression = "'"+Col1+Col2+"'"; 

this would reduce cycle time and update quickly :) View Marc offer

0
source

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


All Articles