将无模式csv转换为C#结构

时间:2016-02-11 22:33:55

标签: c# .net

我接收的数据类似于csv格式,具有不同的值类型(int,double,DateTime,string等),并且是无模式的(列数和值)类型在运行时才知道。

我想将这些数据解析为.NET值类型,并在运行时将其存储在某种结构中。保存这些数据的最佳结构是什么?

我目前将其存储在DataTable中,但从中检索强类型值仍然是一件麻烦事。我想知道是否有更好的想法我可能没有考虑过。

1 个答案:

答案 0 :(得分:1)

尝试创建一个可以保存属性名称的类,以及一组强类型值:

class Container{        
   public string PropertyName { get; set;}
   public DateTime DateTimeValue { get; set;}
   public int IntValue { get; set;}
   public string StringValue { get; set;}
   etc.
} 

对传入值执行检查并将它们放在正确的属性中。

 string propertyName = array[0];
 string propertyValue = array[1];

 Container container = new Container();
 container.PropertyName = propertyName;

 if (int.TryParse(propertyValue, out intVariable))
 {
     container.IntValue = intVariable;
 }
 else if (... ... ...) {}
 else 
 {
     container.StringValue = propertyValue;
 }

构建此对象类型的列表。然后,您可以对使用属性的列表进行排序,或根据需要对对象进行分组。