Replace Key And Values with actual Data from the List

Viewed 70

I Have the following method in C# which takes in a list of columns and list of rows and adds into a dynamic list:

public static List < dynamic > RecordFactoryNew(IEnumerable < Property > columns, DataRowCollection dr) {

    dynamic output = new List < dynamic > ();
    dynamic cust = new ExpandoObject();

    for (int i = 0; i < dr.Count; i++) {
        List < dynamic > list = new List < dynamic > ();

        foreach(var col in columns) {
            SetDateTimeKindUtc(columns, dr[i][col.Name]);
            list.Add(new KeyValuePair < string, dynamic > (col.Name, ((IDictionary < string, dynamic > ) cust)[col.Name] = dr[i][col.Name]));
        }

        output.Add(list);
    }

    return output;
}

Output:

{ Key: 'Links', Value: 'Test.com' },
{ Key: 'ReportID', Value: 21 },
{ Key: 'Verified', Value: true } etc....

Expected Output:

{ Links: 'Test.com', ReportID': 21, Verified: true etc.... },

My return type must remain a List dynamic as the column names are not a fixed set and type.

How would I go about achieving the expected output?

1 Answers
public static List<dynamic> RecordFactoryNew(IEnumerable <Property> columns, DataRowCollection dr) {

    var output = List<dynamic>();

    for (int i = 0; i < dr.Count; i++) {
        IDictionary<string, Object> cust = new ExpandoObject();

        foreach(var col in columns) {
            SetDateTimeKindUtc(columns, dr[i][col.Name]);
            cust.Add(col.Name, dr[i][col.Name]);
        }

        output.Add(list);
    }

    return output;
}
Related