我有一个包含以下数据的CSV文件(无标题)
12,2010,76
2,2000,45
12,1940,30
并且我正在使用以下CSVReader来阅读
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class CSVReader
{
static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
static char[] TRIM_CHARS = { '\"' };
public static List<Dictionary<string,object>> Read(string file)
{
var list = new List<Dictionary<string,object>>();
TextAsset data = Resources.Load (file) as TextAsset;
var lines = Regex.Split (data.text,LINE_SPLIT_RE);
if(lines.Length <= 1) return list;
var header = Regex.Split(lines[0],SPLIT_RE);
for(var i=1; i < lines.Length; i++) {
var values = Regex.Split(lines[i],SPLIT_RE);
if(values.Length == 0 ||values[0] == "") continue;
var entry = new Dictionary<string,object>();
for(var j=0; j < header.Length && j < values.Length; j++ ) {
string value = values[j];
value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\","");
object finalvalue = value;
int n;
float f;
if(int.TryParse(value,out n)) {
finalvalue = n;
} else if (float.TryParse(value,out f)) {
finalvalue = f;
}
entry[header[j]] = finalvalue;
}
list.Add (entry);
}
return list;
}
}
问题在于此CSVReader使用List<Dictionary<string,object>>
,因此,如果没有标题信息,则字典键将变为null或(不太可能)为空字符串。在字典中添加条目时,这两种情况都会导致抛出异常。
我可以将标题添加到CSV文件,但这不是理想的解决方案。