2010-09-14 69 views
0

我需要編寫一個腳本,它將一個列表與一個詞典合併在一起,以創建第三個詞典。我對編程相當陌生,並且在這裏苦於基本知識。使用詞典

到目前爲止,我創建了以下類,它生成一個日期列表。我有另一個生成字典的類,我想基本上創建第三個字典,其中包含第一個列表中不存在的日期和數據。 任何想法我應該如何做到這一點?謝謝。

class StartList: IDisposable 
{ 
    private readonly string[] names = new[] { "name1", "name2", "name3"}; 

    private SqlConnection conn; 
    private Dictionary<string, List<DateTime>> startData = new Dictionary<string, List<DateTime>>(); 

    public StartList() 
    { 
     this.conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NameCon"].ConnectionString); 
     this.conn.Open(); 
    } 

    private void Dispose() 
    { 
     if (this.conn != null) 
     { 
      if (this.conn.State != ConnectionState.Closed) 
      { 
       try 
       { 
        this.conn.Close(); 
       } 
       catch 
       { 
       } 
      } 

      this.conn.Dispose(); 
      this.conn = null; 
     } 
    } 

    public void ImportStartData() 
    { 
     foreach (string name in this.names) 
     { 
      this.startData.Add(name, this.ImportStartData(name)); 
     } 
    } 

    public List<DateTime> ImportStartData(string name) 
    { 
     List<DateTime> result = new List<DateTime>(); 

     string sqlCommand = string.Format("SELECT * FROM {0}_Index ", name); 

     using (SqlCommand cmd = new SqlCommand(sqlCommand, this.conn)) 
     { 
      cmd.CommandType = CommandType.Text; 

      using (SqlDataReader reader = cmd.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        result.Add(reader.GetDateTime(0)); 
       } 
      } 

     } 

     return result; 
    } 

} 
+2

你的方法「ImportStartData」是奇怪的。該方法遍歷「this.names」中的條目,然後繼續將條目添加到自己的「this.names」中。 – 2010-09-14 14:01:20

+0

和'this.names'是'readonly'。我不認爲我理解。 – recursive 2010-09-14 14:18:58

+0

對不起,我在ImportStartData中犯了一個錯誤,應該已經添加到startData中,而不是名稱。謝謝 – Brian 2010-09-14 14:29:33

回答

1

首先,你需要修改下面的代碼塊 來源:

public void ImportStartData() 
    { 
     foreach (string name in this.names) 
     { 
      this.names.Add(name, this.ImportStartData(name)); 
     } 
    } 

要:

public void ImportStartData() 
    { 
     foreach (string name in this.names) 
     { 
      if(!startData.ContainsKey(name)) //If this check is not done, then Dictionary will throw, duplicate key exception. 
      { 
       this.startData.Add(name, this.ImportStartData(name)); 
      } 
     } 
    } 

不管怎麼說,更好的辦法是,如果可能的話先讀以及日期從數據庫,可能到DataTable和n使用LINQ/foreach循環,按名稱對結果進行分組。

+0

感謝Siva的領導。 – Brian 2010-09-14 14:29:56

+0

我不確定你的建議。我可能沒有正確解釋目標。我最終使用從Excel工作表中收集的新數據更新了許多SQL表格。我首先從SQL中提取現有數據,然後將excel數據拖入字典中。然後,我拿出新的字典並刪除已經存在於我們從SQL填充的List中的舊數據。 – Brian 2010-09-14 14:30:29

+0

您的意思是您想要將現有SQL數據與Excel工作表中的數據合併,然後將合併的數據寫回到SQL表中? – 2010-09-14 14:52:33