2016-12-14 78 views
0

我找了一个很好的数据结构的表看起来就像这样:C#寻找用于JSON数据的灵活数据结构

Name | ID | Time | A3 | A2 | D6 | L4 | H1 | ... 
Peter 01 11:01 1 4 8   1 ... 
James 02 11:37 7   5 2 2 ... 
.... 

的名称,ID和时间值的“手动”给予我的工具,所有列之后(“A3”,“A2”,...)从一个JSON字符串来像

{"A3":"7","D6":"5",...} 

我的问题IST,这些JSON值可以有任何名字,我就不说了知道哪些人会产生哪些值(样本中,詹姆斯没有为A2的值)。

哪种类型/结构最适合存储这些变量组合?

当然应该是“易”,以增加新的线路,如果新的价值观“到达”。而且我也希望以后这种结构写入到CSV,但在这里,这不是问题。

我尝试了很多,但是没有设法创建任何易于处理的东西。

在此先感谢!

编辑:我终于用两个答案的组合:

public class ResultData 
{ 
    public string currentName { get; set; } 
    public string currentID { get; set; } 
    public DateTime currentTimestamp { get; set; } 
    public DataTable results { get; set; } 

    public ResultData() 
    { 
     results = new DataTable(); 

     // must have columns 
     results.Columns.Add("Name", typeof(string)); 
     results.Columns.Add("ID", typeof(string)); 
     results.Columns.Add("Timestamp", typeof(DateTime)); 
    } 


    public void AddResult(Dictionary<string, string> resultVars) 
    { 
     // TODO: check if person is already in list 

     DataRow dr = results.NewRow(); 

     // add basics 
     dr["Name"] = currentName; 
     dr["ID"] = currentID; 
     dr["Timestamp"] = currentTimestamp; 

     // check columns 
     foreach (var varName in resultVars) 
     { 
      // add column if needed 
      if (!results.Columns.Contains(varName.Key)) 
      { 
       results.Columns.Add(varName.Key); 
      } 

      // add values 
      dr[varName.Key] = varName.Value; 
     } 

     //finally add row 
     results.Rows.Add(dr); 
    } 
} 

工作对我很好! :-)

回答

0

这里是一个解决方案,它在C#发现,

DataTable类存储数据行和列。这是对System.Data命名空间的一部分。我们添加,选择和遍历存储的数据。

使用的DataTable

using System; 
    using System.Data; 

    class Program 
    { 
     static void Main() 
     { 
     // Get the DataTable. 
     DataTable table = GetTable(); 
     // ... Use the DataTable here with SQL. 
     } 

     /// <summary> 
     /// This example method generates a DataTable. 
     /// </summary> 
     static DataTable GetTable() 
     { 

     // Here we create a DataTable with four columns. 
     DataTable table = new DataTable(); 
     table.Columns.Add("Dosage", typeof(int)); 
     table.Columns.Add("Drug", typeof(string)); 
     table.Columns.Add("Patient", typeof(string)); 
     table.Columns.Add("Date", typeof(DateTime)); 

     // Here we add five DataRows. 
     table.Rows.Add(25, "Indocin", "David", DateTime.Now); 
     table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); 
     table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); 
     table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); 
     table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 
     return table; 
     } 
    } 

还有一个好东西

C#程序的Visual Studio帮助你的视觉数据,

试试这个它有很多的可能性与DataRow类也,其快速和简单的一个保存表格数据。

0

您是否尝试过包含Dictionary属性的类?

public class MyClass{ 
    public int id {get; set;} 
    public string name {get; set;} 
    public Datetime time {get; set;} 
    public Dictionary<string, string> {get;} 
}