簡體   English   中英

在方法中使用兩個值列表作為參數,並生成與兩個列表長度一樣多的對象 C#

[英]Use two lists of values as parameters in a method and generate objects as many as the length of the two lists C#

我有以下兩個功能:

        //-----------------------------------FUNCTION 4-----------------------------------
        /// <summary>
        /// Call the specified procedure that will import file1 in SQL Server
        /// </summary>
        /// <param name="connectionString"> The connection string to SQL server instance</param>
        /// <param name="importedfilepath"> The path of the browsed file</param>
        public static void LoadLayout(string connectionString, string importedfilepath)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (var command = sqlConnection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "createselectedtableinDB";
                    command.Parameters.AddWithValue("@TableName", importedfilepath);
                    command.ExecuteNonQuery();
                    if (command.ExecuteNonQuery() > 0)
                        MessageBox.Show("Selected file was loaded successfully");
                }
            }
        }

        //-----------------------------------FUNCTION 5-----------------------------------
        /// <summary>
        /// Call the specified procedure that will import file2 in SQL Server
        /// </summary>
        /// <param name="connectionString"> The connection string to SQL server instance</param>
        /// <param name="importedfilepath"> The path of the browsed file</param>
        public static void LoadBusinessChecks(string connectionString, string importedfilepath)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (var command = sqlConnection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "createselectedtableinDB";
                    command.Parameters.AddWithValue("@TableName", importedfilepath);
                    command.ExecuteNonQuery();
                    if (command.ExecuteNonQuery() > 0)
                        MessageBox.Show("Selected file was loaded successfully");
                }
            }
        }

如您所見,這兩個函數采用兩個參數(各不相同):

  • 參數 1:到 SQL 服務器的連接字符串
  • 參數 2:文件路徑

有了這兩個參數,我到目前為止還好。 我想要的是進一步優化這兩個功能,基本上只有1個功能而不是這兩個。 為此,我知道我需要以某種方式指定:

  • 產品名稱:
command.CommandText = "createselectedtableinDB"; //can take different values
  • 程序參數和值(2個等長列表)
command.Parameters.AddWithValue("@TableName", importedfilepath); //more than 1 parameter so import a list here

因此,我預期的新變異函數如下所示:

請注意,下面的代碼不正確,但我正在嘗試復制我的直覺,以便您了解我正在嘗試做什么。 下面的代碼將幫助您了解我試圖在高層次上實現的目標。

        public static void LoadFiles(string connectionString, string importedfilepath, string ProcedureName, list ParameterName, list ParameterValue)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (var command = sqlConnection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = ProcedureName;
                    
                    foreach (string parametername in ParameterName)
                    {
                        foreach (string parametervalue in ParameterValue) 
                    {
                            command.Parameters.AddWithValue(parametername, parametervalue ); //Generate as many as the length of the two lists
                    }
                    }
                    command.ExecuteNonQuery();
                    if (command.ExecuteNonQuery() > 0)
                        MessageBox.Show("Selected file was loaded successfully");
                }
            }
        }

從 LoadButton1_Click 調用方法時

        private void LoadButton1_Click(object sender, RoutedEventArgs e)
        {   
            ParameterNamelist = list ["@TableName", "@Username", "@Email"]
            ParameterValuelist = list [importedfilepath, "Nikos", "nikos@stackoverflow.com"]

            var connectionString = SQLServerConnectionDetails();
            LoadFiles(connectionString, FileNameTextBox.Text, "SelectUsernameProcedure", ParameterNamelist, ParameterValuelist);
        }

從 LoadButton2_Click 調用確切方法時

        private void LoadButton2_Click(object sender, RoutedEventArgs e)
        {   
            ParameterNamelist = list ["@TableName", "@ProductName"]
            ParameterValuelist = list [importedfilepath, "Choco"]

            var connectionString = SQLServerConnectionDetails();
            LoadFiles(connectionString, FileNameTextBox.Text, "SelectProductProcedure", ParameterNamelist, ParameterValuelist);
        }

您可以將Dictionary<string, object>傳遞給方法,而不是兩個單獨的列表:

示例詞典:

 Dictionary<string, object> myparams = new Dictionary<string, object>()
 {
    {"@TableName", importedfilepath },
    {"@ProductName", "Choco" }
 };

新方法:

 public static void LoadFiles(string connectionString, string ProcedureName,
          Dictionary<string, object> @params)
 {
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (var command = sqlConnection.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = ProcedureName;
                    
                foreach (string key in @params.Keys)
                {                            
                     command.Parameters.AddWithValue(key, @params[key]); 
                }
                command.ExecuteNonQuery();
                if (command.ExecuteNonQuery() > 0)
                    MessageBox.Show("Selected file was loaded successfully");
            }
        }
 }

既然您聲明要使用上面的偽代碼和兩個列表,那么它會這樣工作,我建議使用上面提供的Dictionary方法,但要滿足您的問題:

//This is not a very safe way
//1. Both lists would need to have the same Count
//2. Parameters names would need to be ordered the same as Parameter values
public static void LoadFiles(string connectionString, string ProcedureName, 
                                List<string> ParameterName, List<object> ParameterValue)
{
       if(ParameterName.Count != ParameterValue.Count) 
          throw new Exception("Lists are of different Count");

       using (SqlConnection sqlConnection = new SqlConnection(connectionString))
       {
            sqlConnection.Open();
            using (var command = sqlConnection.CreateCommand())
            {
               command.CommandType = CommandType.StoredProcedure;
               command.CommandText = ProcedureName;
                    
               for(int i = 0; i < ParameterName.Count; i++)
               {
                    command.Parameters.AddWithValue(ParameterName[i], ParameterValue[i]); //Generate as many as the length of the two lists
               }
                           
                    
                command.ExecuteNonQuery();
                if (command.ExecuteNonQuery() > 0)
                    MessageBox.Show("Selected file was loaded successfully");
            }
        }
}

您可以改用字典

public static bool LoadFiles(string connectionString, string ProcedureName, 
    IReadOnlyDictionary<string, object> parameters)
{
    using var sqlConnection = new SqlConnection(connectionString);
    sqlConnection.Open();
    
     using var command = sqlConnection.CreateCommand();
     command.CommandType = CommandType.StoredProcedure;
     command.CommandText = ProcedureName;
                
     foreach (KeyValuePair<string, object> parameter in parameters)
     {
         command.Parameters.AddWithValue(parameter.Key, parameter.Value);
     }

     return (command.ExecuteNonQuery() > 0);
}

進而

private void LoadButton1_Click(object sender, RoutedEventArgs e)
{   
    var parameters = new Dictionary<string, object>()
    {
        ["@TableName"] = importedfilepath,
        ["@Username"] = "Nikos",
        ["@Email"] = "nikos@stackoverflow.com"
    };

    var connectionString = SQLServerConnectionDetails();
    
    bool commandExecuted = LoadFiles(connectionString,
        "SelectUsernameProcedure", parameters);

    if (commandExecuted)
    {
        MessageBox.Show("Selected file was loaded successfully");
    }
}

暫無
暫無

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

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