通过CSVHelper将具有列动态大小的R/W csv添加到查找表中



我有一个类似的csv数据

>值13值22>值33值N2
标头1 标头2 标头3 值N
Key1 值11 值12值1N
Key2 值21值23值2N
Key3 值31 值32值3N
KeyN 值N1值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();
}
}
}

相关内容

  • 没有找到相关文章

最新更新