2022-06-21

Dynamic group by list data indexes

I want to group by dynamically according to more than one index in a list.

Model

public class MyModel
{
    public string baseTableName { get; set; }
    
    public List<object> columns { get; set; }
    
    public List<List<object>> rows { get; set; }
}

I need to find the indexes of the pk columns list in this model. Then I want to group the data in the rows list by pk columns.

Sample Request

{
    "tableName": "fooTable",
    "columns": [
        "c1",
        "c2",
        "c3"
    ],
    "rows": [
        [
            "1",
            "a",
            "kobe"
        ],
        [
            "2",
            "a",
            "lebron"
        ]
    ]
}

In this sample request, columns c1 and c2 are pk.

Codes

// Returns indexes of pk columns.
var pkColumnIndexes = GetPkIndexes(columns);

var gp = requestObject.rows.GroupBy(gp => new { indx1 = gp[pkColumnIndexes[0]], indx2 = gp[pkColumnIndexes[1]] });
var groupData = gp.Select(s => s.LastOrDefault()).ToList();

--

(gp => new { indx1 = gp[pkColumnIndexes[0]], indx2 = gp[pkColumnIndexes[1]] })

I want to group this part according to indexes.

Can group by keys dynamically created with a for loop?



No comments:

Post a Comment