Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access Dictionary items?

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!

like image 391
salvationishere Avatar asked Jun 07 '10 12:06

salvationishere


People also ask

How can you access elements from the dictionary?

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.

How can I access dictionary without key?

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.


1 Answers

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.

like image 140
Graham Clark Avatar answered Nov 15 '22 17:11

Graham Clark