我有一个类似的csv数据
标头1 | 标头2 | 标头3 | 值N | ||
---|---|---|---|---|---|
Key1 | 值11 | 值12 | >值13值1N | ||
Key2 | 值21 | 值22值23 | 值2N | ||
Key3 | 值31 | 值32 | >值33值3N | ||
KeyN | 值N1 | 值N2值N3 | 值NN |
除了@dbc评论说由于Dictionary<TKey, TValue>
的无序性,项目的顺序可能会改变外,这应该是有效的。
void Main()
{
var lookup_table = new Dictionary<string, Dictionary<string, string>>();
using (var reader = new StringReader(",Header1,Header2,Header3nKey1,value11,value12,value13nKey2,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();
}
}
}