I am developing a C# VS2008 / SQL Server website app and am new to the Dictionary class. Can you please advise on best method of accomplishing this? Here is a code snippet:
SqlConnection conn2 = new SqlConnection(connString);
SqlCommand cmd = conn2.CreateCommand();
cmd.CommandText = "dbo.AppendDataCT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn2;
SqlParameter p1, p2, p3;
foreach (string s in dt.Rows[1].ItemArray)
{
DataRow dr = dt.Rows[1]; // second row
p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]);
p1.SqlDbType = SqlDbType.VarChar;
p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]);
p2.SqlDbType = SqlDbType.VarChar;
p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]);
p3.SqlDbType = SqlDbType.VarChar;
}
but this is giving me compiler error:
The best overloaded method match for 'System.Collections.Generic.Dictionary<string,string>.this[string]' has some invalid arguments
I just want to access each value from "dic" and load into these SQL parameters. How do I do this? Do I have to enter the key? The keys are named "col1", "col2", etc., so not the most user-friendly. Any other tips? Thanks!
Accessing Elements from Dictionary Keys can be used either inside square brackets [] or with the get() method. If we use the square brackets [] , KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.
You just have to use dict. values() . This will return a list containing all the values of your dictionary, without having to specify any key.
A Dictionary
maps objects of one type into objects of another type. In your case you've got a Dictionary<string, string>
. So if you had it initialised like this:
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" }
};
You'd get the value for key2
by doing
dic["key2"]; // gives "value2"
The Dictionary
is strongly-typed, so there's no need for any casting. As Jon Skeet says, you may be better off with a List<string>
here. You can access these by the integer index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With