using System; using System.Collections.Generic; using System.Data; using System.IO; namespace etoy { // KeyValue表结构 // * 0 1 2 3 4 // 0 key value type description tag // 1 AAA 0 int des1 c // 2 BBB 111 int des2 // 3 CCC Hello string des3 s // 4 DDD string des4 // * type 目前仅支持 int & string sealed class KeyValueTableCsvParser { const int START_ROW = 1; public KeyValueTable Parse(DataTable dt, string file) { int rowCount = dt.Rows.Count; int colCount = dt.Columns.Count; if (rowCount <= 0 || colCount < 5) throw new Exception($"KeyValue表结构不合法, Row: {rowCount}, Column: {colCount}"); var row0 = dt.Rows[0]; string key = row0[0].ToString().ToFieldType(); string value = row0[1].ToString().ToFieldType(); string type = row0[2].ToString().ToFieldType(); string description = row0[3].ToString().ToFieldType(); string tag = row0[4].ToString().ToFieldType(); if (key != nameof(key) || value != nameof(value) || type != nameof(type) || description != nameof(description) || tag != nameof(tag)) throw new Exception(); var rows = new List(rowCount); for (int i = START_ROW; i < rowCount; ++i) { var row = dt.Rows[i]; if (string.IsNullOrEmpty(row[0] as string)) // key为empty,不处理此行 continue; var keyValueRow = new KeyValueRow(); keyValueRow.Row = i; for (int j = 0; j < colCount; ++j) { var cellvalue = row[j].ToString().ToCellValue(); var keyValueType = (KeyValueColumn)j; switch (keyValueType) { case KeyValueColumn.Key: keyValueRow.Key = cellvalue; break; case KeyValueColumn.Value: keyValueRow.Value = cellvalue; break; case KeyValueColumn.Type: keyValueRow.Type = cellvalue; break; case KeyValueColumn.Description: keyValueRow.Description = cellvalue; break; case KeyValueColumn.Tag: keyValueRow.Tag = cellvalue?.ToLower() ?? string.Empty; break; default: throw new Exception(); } } rows.Add(keyValueRow); } var table = new KeyValueTable(); table.Name = Path.GetFileNameWithoutExtension(file).ToTableName(); table.Path = file; table.Rows = rows.ToArray(); return table; } } }