1

What is the best way to add unknown values from a list of lists to the columns and rows of a DataTable? I have a lists of lists of objects of data type

public class RegClass
{
    public string parameterName { get; set; }
    public string parameterValue { get; set; }
}

Each time a new 'parameterName' is iterated through a new column of that name should be added with the corresponding 'parameterValue' as a row under it. Otherwise when iterating and when found that an objects 'parameterName' is identical to a column already made, the 'parameterValue' should just be added as a row under the already existing column. If a list does not contain an object with the 'parameterName' equal to an existing column then a blank value should be added.

enter image description here

For example, in the image above the first list would have contained objects of type 'RegClass' with 'parameterNames' of 's2','id' and 'segment'. As these were the first to be added the new columns would be created in the datatable and the 'parameterValues' added. The next list contained objects with type 's2' and 'id' but not 'segment. As the columns were already created, the objects 'parameterValues' are written to the corresponding rows, but as there was no object with 'parameterName' equals to 'segment', a blank value is added. The final list added contains an object of 'parameterName' 'vtoken'. As it is the first time an object with this value has been added a new column is added.

I have tried iterating through the list of lists and getting each unique 'parameterName' and then adding as columns to the datatable.

   List<string> queryParametersList = new List<string>();
    
   List<List<RegClass>> regList = new List<List<RegClass>>();
   
   foreach (var v in regList)
   {
       foreach (var x in v)
       {
           if (!queryParametersList.Contains(x.parameterName))
           {
               queryParametersList.Add(x.parameterName);
           }
       }
   }

   DataTable queryParamsTable = new DataTable();

   foreach (var v in queryParametersList)
   {
        queryParamsTable.Columns.Add(v, typeof(string));         
   }

But now how do I populate the rows of the DataTable?

1 Answer 1

1

you have to loop regList again:

 foreach (var v in regList)
   {
       var row = queryParamsTable.NewRow();
       foreach (var x in v)
       {
           row[x.parameterName] = x.parameterValue;
       }
       queryParamsTable.Rows.Add(row);
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.