Search code examples
c#linqdatatable

Convert a List<object[]> to List<object> where the count of object[] is dynamic


How could we convert a List<object[]> to List<object> where the count of objects in object[] is dynamic(in a single collection it is the same i.e. items[0].count is equal to items[1].count but every different collection could have a dynamic number of item count).

Sample Data: sample data

What I tried so far is if the count of items is constant it can be achieved by the below code

dt.Select().Select(s => s.ItemArray).Select(s => new {a = s[0], b= s[1]}..).ToList()  

But how could we generate the select statement for the dynamic number of columns?

More background on having the dynamic number of columns:
The List<object[]> is generated from dataRows. The reason it is dynamic is because dataTable could have any number of columns.

Any suggestion will be helpful


Solution

  • SelectMany is what you need, then it doesn't matter how many items are contained in each array:

    List<object[]> objectArrays = ...
    List<object> flattenedObjects = objectArrays.SelectMany(arr => arr).ToList(); 
    

    However, in your screenshot i can see that you have a DataTable and you want a list of all fields in all rows, then better use:

    List<object> allFields = dt.AsEnumerable()
      .SelectMany(row => row.ItemArray)
      .ToList();
    

    If you want the most efficient approach:

    List<object> allFields = new(dt.Rows.Count * dt.Columns.Count);
    foreach(DataRow row in dt.Rows) allFields.AddRange(row.ItemArray);