簡體   English   中英

使用字典

[英]Using Dictionary

我需要編寫一個腳本,該腳本將列表與字典合並以創建第三個字典。 我對編程很陌生,並且在這里苦苦學習基礎知識。

到目前為止,我已經創建了以下類,該類生成日期列表。 我還有另一個生成字典的類,我想基本上創建第三個字典,其中包含第一個列表中不存在的日期和數據。 有什么想法我應該怎么做? 謝謝。

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 ,然后使用LINQ / foreach循環按名稱對結果進行分組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM