Dictionary value then key iteration

Advertisements

If I use a dictionary as follows (NB: The dictionary will not change after initialization)

public static void Main()
{
    Dictionary<string, string> mapColumns = new Dictionary<string, string>()
    {
        {"IDCode", "EmployeeUID"},
        {"firstName", "Name"},
        {"lastname", "Surname"}
    };
    //Key: datatable field name (source data) - from a flat file (so no concerns about injection etc)
    //Value: destination table field names

    DataTable sourceData = ReadFromFile(@"\\server\shares\staff.csv");

    StringBuilder tsql = new StringBuilder(1024);
    tsql.AppendLine("insert into staffdata (");
    foreach (var value in mapColumns.Values)
    {
        tsql.Append($"{value},");
    }
    tsql.Length--;
    tsql.Append(") values");

    foreach (DataRow row in sourceData.Rows)
    {
        tsql.AppendLine().Append("(");
        foreach (string key in mapColumns.Keys)
        {
            tsql.Append($"'{row[key]}',");
        }
        tsql.Length--;
        tsql.Append("),");
    }
    tsql.Length--;

    InsertIntoDatabase(tsql.ToString());
}

I know that dictionary keyvalue pairs ordering is undeterministic, so the order the pairs are inserted is not necessarily maintained.
That is not a problem in the slightest.

Is it therefore possible that the order of the pairs could get "shuffled" up between the Value iteration and then Key Iteration?

I am trying to fully understand how the undetermined ordering of dictionary iteration works

For example – source data

IDCode FirstName LastName
A104   Joe       Soap
Q187   Martin    Smith

I expect (and am happy with):

EmployeeUID Name    Surname
Q187        Martin  Smith
A104        Joe     Soap

However, could it potentially insert as: (KeyValue pairs change order after Value iteration)

EmployeeUID Name    Surname
Soap        Joe     A104
Smith       Martin  Q187

I have run my own tests, and have not found that they change, but maybe in 1000000 iterations I got "lucky" or my tests were flawed in some way

>Solution :

The Keys and Values properties are documented to be in the same order:

The order of the keys in the Dictionary<TKey,TValue>.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary<TKey,TValue>.ValueCollection returned by the Values property.

Mirrored by the Values docs:

The order of the values in the Dictionary<TKey,TValue>.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary<TKey,TValue>.KeyCollection returned by the Keys property.

Barring modifications (add/remove) between calls, of course.

This is because both properties iterate over the internal entries of the dictionary.

That being said: a dictionary is meant for lookup, not enumeration. So you’d better use a more fitting collection, like a list of tuples:

var mapColumns = new List<(string Title, string ColumnName)>
{
    ("EmployeeUID", "IDCode"),
    ("Name", "firstName"),
    ("Surname", "lastname")
}.AsReadOnly();

Leave a ReplyCancel reply