I have a IEnumerable
of anonymous type as result of a LINQ join operation. Some of the values of the list are:
{ CellId = 0, CellIndex = "1", CellDataType = "String", CellValue = "Id", RowNumber = 0 }
{ CellId = 1, CellIndex = "2", CellDataType = "String", CellValue = "first_name", RowNumber = 0 }
{ CellId = 2, CellIndex = "3", CellDataType = "String", CellValue = "age", RowNumber = 0 }
{ CellId = 3, CellIndex = "4", CellDataType = "String", CellValue = "child_name", RowNumber = 0 }
{ CellId = 4, CellIndex = "5", CellDataType = "String", CellValue = "child_age", RowNumber = 0 }
{ CellId = 5, CellIndex = "1", CellDataType = "Number", CellValue = "1", RowNumber = 1 }
{ CellId = 6, CellIndex = "2", CellDataType = "String", CellValue = "john", RowNumber = 1 }
.
.
.
(The data is coming from a excel sheet) you can see that the objects with rowNumber = 0 have the column names of the table.
from the spreadsheet you can notice that John (id=1) has 3 children, so I would like to group by id and have something like:
Id = 1
first_name = "john", age = 30, child_name = "Andy", child_age = 4
first_name = "john", age = 30, child_name = "Anna", child_age = 6
first_name = "john", age = 30, child_name = "Lily", child_age = 8
Id = 2
first_name = "Emily", age = 32, child_name = "Harry", child_age = 3
first_name = "Emily", age = 32, child_name = "David", child_age = 3
Id = 3
first_name = "Peter", age = 40, child_name = "Carol", child_age = 2
I assume that Linq GroupBy can do this. The problem is:
The elements of the list are of anonymous type and its properties are generic objects. CellId, CellIndex, RowNumber will always be integers so I could use cast, but CellValue is not defined, it could be string, integer, etc.
I can produce an IEnumerable of Anonymous Type <int, int, string, string, int>
. I am basically converting CellId to int, CellIndex to int, CellValue to string, CellDataType to string and RowNumber to int. But I am not sure still how can I do the grouping.
How can I group them?
To compare that the Id are equals I need to look for CellIndex = 1 (which corresponds to the column name Id) and then use the CellValue property (of the same anonymous type element) to see if it is equal.
Basically I need to group by CellValue but only for those that have a CellIndex = 1.
Any suggestions?