C# 这是方法体中多键字典的有效代码吗?

C# 这是方法体中多键字典的有效代码吗?,c#,.net-3.5,dictionary,C#,.net 3.5,Dictionary,我只想问一下: 下面的代码是否有效 有没有更好的方法来处理这个问题 如果需要tablename/fieldname对的其他值,如何编码 我们需要使用包含以下内容的多键词典(TableName、FieldName、FieldValue) 我搜索了一些答案,但到目前为止我找到的答案不适用于我们的设置。我们正在使用3.5,所以还没有可用的元组。我们还将这个脚本逻辑与一个只允许在方法体“内部”进行编码的应用程序集成,因此我们受到限制,无法创建单独的类/结构等。我们的设置是C#/VS 2010 感谢您的帮

我只想问一下:

  • 下面的代码是否有效
  • 有没有更好的方法来处理这个问题
  • 如果需要tablename/fieldname对的其他值,如何编码
  • 我们需要使用包含以下内容的多键词典(TableName、FieldName、FieldValue)

    我搜索了一些答案,但到目前为止我找到的答案不适用于我们的设置。我们正在使用3.5,所以还没有可用的元组。我们还将这个脚本逻辑与一个只允许在方法体“内部”进行编码的应用程序集成,因此我们受到限制,无法创建单独的类/结构等。我们的设置是C#/VS 2010

    感谢您的帮助。提前谢谢

    Dictionary<string, Dictionary<string, string>> tableList = new Dictionary<string, Dictionary<string, string>>();
    Dictionary<string, string> fieldList = new Dictionary<string, string>();
    
    // add fields to field list, then add the field lists to the corresponding table list
    // clear field list for next table
    // values are just hardcoded here to simplify, but is being read from actual objects in the application
    
    fieldList.Add("Field1", "abc");
    fieldList.Add("Field2", "def");
    fieldList.Add("Field3", "ghi");
    fieldList.Add("Field4", "jkl");
    
    tableList.Add("Table1", new Dictionary<string, string>(fieldList));
    fieldList.Clear();
    
    fieldList.Add("Field1", "xyz");
    fieldList.Add("Field2", "uvw");
    fieldList.Add("Field3", "rst");
    
    tableList.Add("Table2", new Dictionary<string, string>(fieldList));
    fieldList.Clear();
    
    fieldList.Add("Field1", "123");
    fieldList.Add("Field2", "456");
    
    tableList.Add("Table3", new Dictionary<string, string>(fieldList));
    fieldList.Clear();
    
    // Display tables and corresponding fields                          
    
    foreach (KeyValuePair<string, Dictionary<string, string>> fieldList4 in tableList)
    {
        foreach (KeyValuePair<string, string> fieldList5 in fieldList4.Value)
        {
            txtMessage.Text = txtMessage.Text + "\r\nTable=" + fieldList4.Key + ", Field=" + fieldList5.Key + " - " + fieldList5.Value;
        }
    }
    
    // Try to find tables and fields in the lists, and list the value if found
    
    string tableToFind = "Table2";
    string fieldToFind = "Field2";
    Dictionary<string, string> tableFields = new Dictionary<string, string>();
    
    if (tableList.Keys.Contains(tableToFind) == true)
    {
        txtMessage.Text = txtMessage.Text = "\r\nTable=" + tableToFind + " exist in table list";
        tableList.TryGetValue(tableToFind, out tableFields);
    
        if (tableFields.Keys.Contains(fieldToFind) == true)
        {
            foreach(KeyValuePair<string, string> fieldData  in tableFields)
            {
                if (fieldData.Key == fieldToFind)
                {
                    txtMessage.Text = txtMessage.Text + "\r\nTable=" + tableToFind + ", Field=" +  fieldData.Key + 
                                                        " with value=" + fieldData.Value + " exist in table list";
                    break;
                }
            }
        }
    }
    
    Dictionary tableList=newdictionary();
    字典字段列表=新字典();
    //将字段添加到字段列表中,然后将字段列表添加到相应的表列表中
    //清除下一个表的字段列表
    //这里的值只是为了简化而硬编码的,但是从应用程序中的实际对象中读取
    字段列表。添加(“字段1”、“abc”);
    字段列表。添加(“字段2”、“定义”);
    字段列表。添加(“字段3”、“ghi”);
    字段列表。添加(“字段4”、“jkl”);
    tableList.Add(“Table1”,新词典(fieldList));
    fieldList.Clear();
    字段列表。添加(“字段1”、“xyz”);
    字段列表。添加(“字段2”、“uvw”);
    字段列表。添加(“字段3”、“rst”);
    tableList.Add(“Table2”,新词典(字段列表));
    fieldList.Clear();
    字段列表。添加(“字段1”、“123”);
    字段列表。添加(“字段2”、“456”);
    tableList.Add(“Table3”,新词典(fieldList));
    fieldList.Clear();
    //显示表格和相应字段
    foreach(表列表中的KeyValuePair字段列表4)
    {
    foreach(字段列表4.Value中的KeyValuePair字段列表5)
    {
    txtMessage.Text=txtMessage.Text+“\r\n表格=“+fieldList4.Key+”,Field=“+fieldList5.Key+”-“+fieldList5.Value;
    }
    }
    //尝试在列表中查找表和字段,如果找到,请列出值
    字符串tableToFind=“Table2”;
    字符串fieldToFind=“Field2”;
    Dictionary tableFields=新字典();
    if(tableList.Keys.Contains(tableToFind)==true)
    {
    txtMessage.Text=txtMessage.Text=“\r\n表格=“+tableToFind+”存在于表格列表中”;
    tableList.TryGetValue(tableToFind,out tableFields);
    if(tableFields.Keys.Contains(fieldToFind)=true)
    {
    foreach(表字段中的KeyValuePair字段数据)
    {
    if(fieldData.Key==fieldToFind)
    {
    txtMessage.Text=txtMessage.Text+“\r\n表格=“+tableToFind+”,字段=“+fieldData.Key+
    “with value=“+fieldData.value+”存在于表列表中”;
    打破
    }
    }
    }
    }
    
    我认为这么多字典不会“有效”

    我认为最好的方法是将值多次添加到同一个字典中-假设您希望能够根据其中一个标记(不是全部)对它们进行索引:

    否则,如果要根据所有标记对它们进行索引,请使用连接字符(如
    '\0'

    dictionary.Add("Table1\0Field1", "xxx");
    

    我认为这么多字典不会“有效”

    我认为最好的方法是将值多次添加到同一个字典中-假设您希望能够根据其中一个标记(不是全部)对它们进行索引:

    否则,如果要根据所有标记对它们进行索引,请使用连接字符(如
    '\0'

    dictionary.Add("Table1\0Field1", "xxx");
    

    您可以使用编译器为您创建一个复合密钥:使用匿名类型

    var dictionary = new Dictionary<Object, int>();
    
    dictionary.Add(new{Text="A", Number=1}, 1);
    dictionary.Add(new{Text="A", Number=2}, 3);
    dictionary.Add(new{Text="B", Number=1}, 4);
    dictionary.Add(new{Text="B", Number=2}, 5);
    
    var x = dictionary[new{Text="B", Number=2}];
    
    var dictionary=newdictionary();
    添加(新的{Text=“A”,Number=1},1);
    添加(新的{Text=“A”,数字=2},3);
    添加(新的{Text=“B”,数字=1},4);
    添加(新的{Text=“B”,数字=2},5);
    var x=字典[new{Text=“B”,Number=2}];
    

    C#将根据您的字段实现Equals和GetHashcode。因此,您确实会得到一个按预期运行的密钥。

    您可以使用编译器为您创建一个复合密钥:使用匿名类型

    var dictionary = new Dictionary<Object, int>();
    
    dictionary.Add(new{Text="A", Number=1}, 1);
    dictionary.Add(new{Text="A", Number=2}, 3);
    dictionary.Add(new{Text="B", Number=1}, 4);
    dictionary.Add(new{Text="B", Number=2}, 5);
    
    var x = dictionary[new{Text="B", Number=2}];
    
    var dictionary=newdictionary();
    添加(新的{Text=“A”,Number=1},1);
    添加(新的{Text=“A”,数字=2},3);
    添加(新的{Text=“B”,数字=1},4);
    添加(新的{Text=“B”,数字=2},5);
    var x=字典[new{Text=“B”,Number=2}];
    

    C#将根据您的字段实现Equals和GetHashcode。因此,您确实得到了一个按预期运行的密钥。

    代码中存在大量问题和低效

  • 如果要创建多个词典,请直接创建词典。不要使用单独的实例来填充值并从中复制

  • 不要在这样的循环中使用字符串连接。使用
    StringBuilder
    或其他类似机制来构建字符串。您的值已经存在于一个集合中,因此将
    String.Join()
    与LINQ结合使用可以清除这些值

  • 至少可以说,从字典中获取值的方法很尴尬。通常您会单独使用
    TryGetValue()
    来尝试读取密钥。您的代码使用不正确。如果要检查字典中是否存在键(使用
    Contains()
    ),那么使用
    TryGetValue()
    就没有意义了。更糟糕的是,您这样做了,然后通过迭代键值对在内部字典中手动搜索键

  • 典型的模式如下所示:

    DictValueType value;
    if (myDict.TryGetValue(key, out value))
    {
        // key was in the dictionary, the value is stored in the `value` variable
    }
    
    var tableList = new Dictionary<string, Dictionary<string, string>>
    {
        { "Table1", new Dictionary<string, string>
                    {
                        { "Field1", "abc" },
                        { "Field2", "def" },
                        { "Field3", "ghi" },
                        { "Field4", "jkl" },
                    }
        },
        { "Table2", new Dictionary<string, string>
                    {
                        { "Field1", "xyz" },
                        { "Field2", "uvw" },
                        { "Field3", "rst" },
                    }
        },
        { "Table3", new Dictionary<string, string>
                    {
                        { "Field1", "123" },
                        { "Field2", "456" },
                    }
        },
    };
    
    // Display tables and corresponding fields
    txtMessage.Text = String.Join("\r\n",
        tableList.SelectMany(table =>
            table.Value.Select(fieldList =>
                String.Format("Table={0}, Field={1} - {2}",
                    table.Key, fieldList.Key, fieldList.Value)
            )
        ).ToArray()
    );
    
    // (I hope you have this in a separate method)
    // Try to find tables and fields in the lists, and list the value if found
    string tableToFind = "Table2";
    string fieldToFind = "Field2";
    
    var builder = new StringBuilder(txtMessage.Text); // mostly useful if you have a 
                                                      // lot of different strings to add
    Dictionary<string, string> foundTable;
    if (tableList.TryGetValue(tableToFind, out foundTable))
    {
        builder.AppendLine()
            .Append("Table=" + tableToFind + " exist in table list");
    
        string foundField;
        if (foundTable.TryGetValue(fieldToFind, out foundField))
        {
            builder.AppendLine()
                .AppendFormat("Table={0}, Field={1} with value={2} exist in table list",
                    tableToFind, fieldToFind, foundField);
        }
    }
    txtMessage.Text = builder.ToString();
    
    您可以像这样更高效地编写代码:

    DictValueType value;
    if (myDict.TryGetValue(key, out value))
    {
        // key was in the dictionary, the value is stored in the `value` variable
    }
    
    var tableList = new Dictionary<string, Dictionary<string, string>>
    {
        { "Table1", new Dictionary<string, string>
                    {
                        { "Field1", "abc" },
                        { "Field2", "def" },
                        { "Field3", "ghi" },
                        { "Field4", "jkl" },
                    }
        },
        { "Table2", new Dictionary<string, string>
                    {
                        { "Field1", "xyz" },
                        { "Field2", "uvw" },
                        { "Field3", "rst" },
                    }
        },
        { "Table3", new Dictionary<string, string>
                    {
                        { "Field1", "123" },
                        { "Field2", "456" },
                    }
        },
    };
    
    // Display tables and corresponding fields
    txtMessage.Text = String.Join("\r\n",
        tableList.SelectMany(table =>
            table.Value.Select(fieldList =>
                String.Format("Table={0}, Field={1} - {2}",
                    table.Key, fieldList.Key, fieldList.Value)
            )
        ).ToArray()
    );
    
    // (I hope you have this in a separate method)
    // Try to find tables and fields in the lists, and list the value if found
    string tableToFind = "Table2";
    string fieldToFind = "Field2";
    
    var builder = new StringBuilder(txtMessage.Text); // mostly useful if you have a 
                                                      // lot of different strings to add
    Dictionary<string, string> foundTable;
    if (tableList.TryGetValue(tableToFind, out foundTable))
    {
        builder.AppendLine()
            .Append("Table=" + tableToFind + " exist in table list");
    
        string foundField;
        if (foundTable.TryGetValue(fieldToFind, out foundField))
        {
            builder.AppendLine()
                .AppendFormat("Table={0}, Field={1} with value={2} exist in table list",
                    tableToFind, fieldToFind, foundField);
        }
    }
    txtMessage.Text = builder.ToString();
    
    var tableList=新字典
    {
    {“表1”,新词典
    {
    {“字段1”,“abc”},
    {“Field2”,“def”},
    {“字段3”,“ghi”},
    {“Field4”,“jkl”},
    }
    },
    {“表2”,新词典
    {
    {“Field1”,“xy”