Lambda expression for Untivoting DataTable

I am reading data from an excel sheet in the following format -

enter image description here

and I need to save the data as follows:

enter image description here

I am trying to do this with the Linq lambda expression, but I think I will not go anywhere with this.

What I tried -

        DataTable dataTable= ReadExcel();
        var dt = dataTable.AsEnumerable();

        var resultSet = dt.Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
                        .GroupBy(x =>
                                    new
                                    {
                                        Month = x.Field<String>("Month"),
                                        ProjectCode = x.Field<String>("Project_Code"),
                                        //change designation columns into row data and then group on it 
                                        //Designation = 
                                    }
                                );
                        //.Select(p =>
                        //            new
                        //            {
                        //                Month= p.d
                        //            }
                        //        );`
+4
source share
1 answer

I would use ToDictionary with a predefined set of name names:

private static readonly string[] designationNames = {"PA","A","SA","M","SM","CON"};
void Function()
{
    /* ... */
    var resultSet = dt.AsEnumerable().Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
            .Select(x =>
                new
                {
                    Month = x.Field<String>("Month"),
                    ProjectCode = x.Field<String>("Project_Code"),
                    Designations = designationNames.ToDictionary(d => d, d => x.Field<int>(d))
                }
            );
}

This is a normalized version. If you want it to be flat, use:

private static readonly string[] designationNames = {"PA","A","SA","M","SM","CON"};

void Function()
{
    /* ... */
    var resultSet = dt.AsEnumerable().Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
        .Select(x =>
            designationNames.Select(
                d =>
                    new
                    {
                        Month = x.Field<String>("Month"),
                        ProjectCode = x.Field<String>("Project_Code"),
                        Designation = d,
                        Count = x.Field<int>(d)
                    }
            )
        ).SelectMany(x => x).ToList();
}

If the type is not always int, you can use x.Field<String>(d)and check its validity instead .

+2
source

Source: https://habr.com/ru/post/1668910/


All Articles