Kristielingg
Kristielingg

Reputation: 51

How to split data to rows and columns in C#

My program works with two Dictionary<string, double>, edge case is when only one dictionary is present

Format of each dictionary is shown below:

Key Value
a-b 0
a-c 1
a-d 2
e-b 3
e-c 4
e-d 5

I want to transform the data to below format, and if working with 2 dictionaries, ensure that the two dictionaries have the same keys so that they can be presented side by side on csv(last picture), and compute difference.

Key b c d
a 0 1 2
e 3 4 5

enter image description here

I have no idea how to do this programmatically, (and handle the edge case as well)

My idea thus far:

  1. Find col header ('a' in example)
  2. Get List from each dictionary containing these col headers.
  3. each row will be col header + all values in the List returned from (2)
  4. Repeat step 1-3

Any help will be appreciated, thank you.

Upvotes: 0

Views: 385

Answers (1)

Tan
Tan

Reputation: 119

I use DataTable to parse data from Dictionary,you can use the idea and write directly to csv file or improve it:

Dictionary<string, double> dict = new Dictionary<string, double>();
dict.Add("a-b", 0);
dict.Add("a-c", 1);
dict.Add("a-d", 2);
dict.Add("e-b", 3);
dict.Add("e-c", 4);
dict.Add("e-d", 5);

DataTable data = new DataTable();
data.Columns.Add("Key");

int i = 0;
Dictionary<string, int> indexKey = new Dictionary<string, int>();

foreach (var d in dict)
{
    var keys = d.Key.Split('-');
    if (!indexKey.Keys.Contains(keys[0]))
    {
        indexKey[keys[0]] = i++;
        data.Rows.Add(data.NewRow()); 
        data.Rows[indexKey[keys[0]]]["Key"] = keys[0];
    }

    if (!data.Columns.Contains(keys[1]))
        data.Columns.Add(keys[1]);

    data.Rows[indexKey[keys[0]]][keys[1]] = d.Value;
}

See the result of the example here

Upvotes: 2

Related Questions