如果我按如下方式使用词典(注意:词典在初始化后不会更改)

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());
}

我知道字典关键字值对的排序是不确定的,因此插入对的顺序不一定保持不变. 这一点都不是问题.

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

我正试图完全理解词典迭代的未确定顺序是如何工作的

例如-源数据

IDCode FirstName LastName
A104   Joe       Soap
Q187   Martin    Smith

我期待(也很高兴):

EmployeeUID Name    Surname
Q187        Martin  Smith
A104        Joe     Soap

然而,它是否可能插入为:(KeyValue对在值迭代后更改顺序)

EmployeeUID Name    Surname
Soap        Joe     A104
Smith       Martin  Q187

我已经运行了自己的测试,没有发现它们会发生变化,但也许在1000000次迭代中我很幸运,或者我的测试在某些方面有缺陷

推荐答案

KeysValues属性为documented to be in the same order:

Dictionary<TKey,TValue>.KeyCollection中键的顺序未指定,但it is the same order作为由Values属性返回的Dictionary<TKey,TValue>.ValueCollection中的关联值.

Values docs个镜像:

Dictionary<TKey,TValue>.ValueCollection中的值的顺序未指定,但它与Keys属性返回的Dictionary<TKey,TValue>.KeyCollection中的关联键的顺序相同.

当然,禁止在调用之间进行修改(添加/删除).

这是因为这两个属性都迭代字典的内部条目.

话虽如此:词典是用来查找的,而不是用来列举的.因此,您最好使用更合适的集合,如元组列表:

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

Csharp相关问答推荐

在C#中使用in修饰符

. NET 8使用COM向VB6公开

如何在C#中使用正则表达式抓取用逗号分隔的两个单词?

未找到任何HTTP触发器.成功部署Azure Functions Project后(c#)

如何使用MailKit删除邮箱?

使用Entity Framework6在对象中填充列表会导致列表大多为空

带有可选参数的模拟方法返回意外的不同值,具体取决于可选的默认值

交替的奇数

JsonPath在Newtonsoft.Json';S实现中的赋值

{ or ; expected error如何解决此问题

如何从Entity Framework Core中填充ListIInterface

ReadOnlyMemory访问基础索引的替代方案

如何在特定环境中运行dotnet测试?

Linq SELECT的多条指令

如何使用LINQ在C#中填充列表列表?

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

单位中快照的倾斜方向

如何在JSON:API中定义的&过滤查询参数系列&标准的GET请求中传递多个相关参数?

我是否以错误的方式使用了异步延迟初始化?

使用c#中的Windows 10关机消息