Search code examples
c#datatable

Still include rows where no matching values found


I have got 2 tables, one with the columns:

  • ItemId
  • Number
  • Title
  • CreatedDate
  • LastModifiedDate

And the other one with the columns:

  • ItemId
  • Title
  • ItemTitle

What I am trying to do is create a new datatable that clones the first one with the column "Function" added, the values for this column will come from the ItemTitle column from the 2nd dataTable.

I am doing this like so:

DataTable test = dtFinal.Clone();
test.Columns.Add("Function");

foreach (DataRow row in dtFinal.Rows)
{
    DataRow[] FunctionData = customPropertiesTable.Select(string.Format("ItemId='{0}' AND Title ='Function'", Convert.ToString(row["ItemId"])));

    if (FunctionData != null && FunctionData.Length > 0)
    {
        string detail = FunctionData[0]["ItemTitle"].ToString();
        var lst = row.ItemArray.ToList();
        lst.Add(detail);
        test.Rows.Add(lst.ToArray());

    }

}

Now this does work but it means that the new table will only show rows where that condition is met, what I would like to do is have it that the new table will still include the rows where the condition was not met so I could end with something like:

enter image description here

Where the function value of the row could be blank if the condition wasn't met. How could I update what I have done to do this?


Solution

  • I managed to solve this, it just simply needs to be:

    foreach (DataRow row in dtFinal.Rows)
    {
        DataRow[] FunctionData = customPropertiesTable.Select(string.Format("ItemId='{0}' AND Title ='Function'", Convert.ToString(row["ItemId"])));
    
    if (FunctionData != null && FunctionData.Length > 0)
    {
        string detail = FunctionData[0]["ItemTitle"].ToString();
        var lst = row.ItemArray.ToList();
        lst.Add(detail);
        test.Rows.Add(lst.ToArray());
    
    }   else {
            string detail = "";
            var lst = row.ItemArray.ToList();
            lst.Add(detail);
            test.Rows.Add(lst.ToArray());
        }
    

    }