使用词典
问题描述:
我需要编写一个脚本,它将一个列表与一个词典合并在一起,以创建第三个词典。我对编程相当陌生,并且在这里苦于基本知识。使用词典
到目前为止,我创建了以下类,它生成一个日期列表。我有另一个生成字典的类,我想基本上创建第三个字典,其中包含第一个列表中不存在的日期和数据。 任何想法我应该如何做到这一点?谢谢。
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;
}
}
答
首先,你需要修改下面的代码块 来源:
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循环,按名称对结果进行分组。
你的方法“ImportStartData”是奇怪的。该方法遍历“this.names”中的条目,然后继续将条目添加到自己的“this.names”中。 – 2010-09-14 14:01:20
和'this.names'是'readonly'。我不认为我理解。 – recursive 2010-09-14 14:18:58
对不起,我在ImportStartData中犯了一个错误,应该已经添加到startData中,而不是名称。谢谢 – Brian 2010-09-14 14:29:33