Search code examples
c#datatableexpressionformula

DataTable expression refering to other DataTable column


I have 2 DataTables, DT1 and DT2.

DT1 has columns A1, B1 and DT2 has columns A2, B2. I'd like to add an expression to A1like A1 = A2 + B2

Is this possible to do without joining or merging the 2 DataTables, this is similar to the way spreadsheets operate?.

Is there any other way to do this, any other data structures or techniques apart from DataTable that would get this done?.

I see that a DataTable won't be able the deduce from a string the tables that the columns belong to? Is it possible that we can add these 2 DataTables to a DataSet and then do the expression referring to tables present in the DataSet.

Edit:

I have used addition as an example however the expressions can have multiple combinations of math and logic operators and sometimes basic math functions.


Solution

  • See code below

                DataTable dt1 = new DataTable();
                dt1.Columns.Add("ID", typeof(string));
                dt1.Columns.Add("A1", typeof(int));
                dt1.Columns.Add("B1", typeof(int));
    
                DataTable dt2 = new DataTable();
                dt2.Columns.Add("ID", typeof(string));
                dt2.Columns.Add("A2", typeof(int));
                dt2.Columns.Add("B2", typeof(int));
    
                DataSet ds = new DataSet()
                ds.Tables.Add(dt1);
                ds.Tables.Add(dt2);
    
                foreach(DataRow row in dt1.AsEnumerable())
                {
                    DataRow match = dt2.AsEnumerable().Where(x => x.Field<string>("ID") == row.Field<string>("ID")).First();
                    row["A1"] = match.Field<int>("A2") + match.Field<int>("B2");
    
                }