2010-09-14 92 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