2016-12-14 80 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;} 
}