Home > OS >  Passing a list of <string>,<object> parameters to a method C#
Passing a list of <string>,<object> parameters to a method C#

Time:09-25

I have the following parameter being passed. Notice the second parameters contains int and string:

(It does not always have to be Area and CustomerName, it can be any names)

UpdateCustomer(customerId, new { Area = 23, CustomerName = "Bob Smith" });

Here is the function

public void UpdateCustomer(int customerId,
                           dynamic parameters)  // Is is correct to define it as "dynamic" or should it be something else?

My question is how would I do a foreach on the parameters and extract both the name/value of each parameter?

This is giving me an error on the foreach line:

// Setup Parameters
foreach (var v in (parameters as dynamic))
{
    if (v is KeyValuePair<string, string>)
    {
        // Do stuff
    }
    else if (v is KeyValuePair<string, int>)
    {
        // Do stuff
    }
    else throw new InvalidOperationException();
}

Thanks before hand

CodePudding user response:

Based on the method name maybe passing an action to update a customer is a suitable option for you? Something like this:

public void UpdateCustomer(int id, Action<Customer> action)
{
    Customer customer = ...// get customer
    action(customer);
}

And usage which will be a little bit more wordy but still:

UpdateCustomer(1, customer =>
{
    customer.Area = 23;
    customer.CustomerName = "Bob Smith";
});

CodePudding user response:

I would pass the parameters as an object (there is no need to pass it as a dynamic) and iterate over its properties using Reflection. From there you can get the name, value, and type, and use them, for example, to create a parameters collection for a database call, as in this example:

public DataTable RunQuery(string connectionString, string storedProcedure, object parameters)
{
    var type = parameters.GetType();
    var properties = type
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Where(p => p.DeclaringType == type)
        .ToArray();
    var sqlParameters = properties
        .Select
        (
            p => new SqlParameter
            {
                SqlDbType = p.PropertyType.ToSqlDbType(),
                ParameterName = p.Name,
                Value = p.GetValue(parameters)
            }
        )
        .ToArray();

    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (var command = new SqlCommand { Connection = connection })
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText = storedProcedure;
            command.Parameters.AddRange(sqlParameters);

            using (var reader = command.ExecuteReader())
            {
                var table = new DataTable();
                table.Load(reader);
                return table;
            }
        }
    }
}

You can then pass an anonymous object as the parameters.

RunQuery(GetConnectionString(), "UpdateCustomer",  new { Area = 23, CustomerName = "Bob Smith" });
  • Related