Except for @dbc comment that the order of the items may change due to the unordered nature of Dictionary<TKey, TValue>, this should work.
void Main()
{
var lookup_table = new Dictionary<string, Dictionary<string, string>>();
using (var reader = new StringReader(",Header1,Header2,Header3\nKey1,value11,value12,value13\nKey2,value21,value22,value23"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Read();
csv.ReadHeader();
var headerLength = csv.Context.Reader.HeaderRecord.Length;
var header = csv.Context.Reader.HeaderRecord;
while (csv.Read())
{
var key = csv.GetField(0);
lookup_table.Add(key, new Dictionary<string, string>());
for (int i = 1; i < headerLength; i++)
{
lookup_table[key][header[i]] = csv.GetField(i);
}
}
}
using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
{
var headers = lookup_table.First().Value.Keys.ToList();
csv.WriteField(string.Empty);
foreach (var header in headers)
{
csv.WriteField(header);
}
csv.NextRecord();
foreach (KeyValuePair<string, Dictionary<string, string>> entry in lookup_table)
{
csv.WriteField(entry.Key);
for (int i = 0; i < headers.Count; i++)
{
csv.WriteField(entry.Value[headers[i]]);
}
csv.NextRecord();
}
}
}