【问题标题】:How to add and name key–value pairs to a dictionary dynamically? C#如何动态地将键值对添加和命名到字典中? C#
【发布时间】:2018-08-20 15:31:05
【问题描述】:

我创建了一个名为“sGC”的字典,它有一个字符串键和一个包含 2 个字符串列表的元组值。

Dictionary<string, Tuple<List<string>, List<string>>> sGC = new Dictionary<string, Tuple<List<string>, List<string>>>();

我想向此字典添加新键,这些键是来自 DataTable DataRow (DR) 的串联字符串。如果满足某个条件,则来自 DR 的字符串将进入元组的 Item1 或 Item2。

此代码在遍历 DataTable 的 foreach 循环中执行,如果该行满足 if 语句条件,则在某些行上停止。

var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
dicTup.Item2.Add(DR["PupilID"].ToString());
sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);

这是向字典添加新的动态命名键的最佳方式吗?

我相信这个 JavaScript 线程的最佳答案是我在 C# 中寻找的答案:How to create dictionary and add key–value pairs dynamically?

完整代码如下。

foreach (DataRow DR in MainData.DataTable.Rows)
            {   
                //Rows containing a symbol mark score
                if ((DR["CN"].ToString() == "LC") && (DR["AW2"].ToString() != ""))
                {
                    //Store male results
                    //If the Subject Name + Level Code is already a key in the dictionary, append to Tuple List 1
                    //If key does not exist in Dictionary, create new DictKey and value
                    if (DR["PG"].ToString() == "Male")
                    {                                           
                        if (sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
                        {                           
                            sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item1.Add(DR["PID"].ToString());
                        }                           

                        else
                        {
                            var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
                            dicTup.Item1.Add(DR["PID"].ToString());
                            sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);                           
                        }
                    }

                    //Store female results
                    //If the Subject Name + Level Code is already a key in the dictionary, append to Tuple List 2
                    //If key does not exist in Dictionary, create new DictKey and value                     
                    if (DR["PG"].ToString() == "Female")
                    {                                           
                        if (sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
                        {                               
                            sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item2.Add(DR["PID"].ToString());           
                        }                           

                        else
                        {
                            var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
                            dicTup.Item2.Add(DR["PupilID"].ToString());
                            sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);
                        }                                                   
                    }                                                                       
                }

新编辑和格式化的代码:

    private void storeMarkSheetData()
    {   
        if (MainData.DataTable != null)
        {

            if(subjectGradeCounts.Count == 0)
            {
                foreach (DataRow DR in MainData.DataTable.Rows)
                {     
                    string cN   = DR["ColumnName"].ToString();
                    string aW2  = DR["AssessmentAwarded2"].ToString();
                    string cSN  = DR["ClassSubjectName"].ToString();
                    string pID  = DR["PupilID"].ToString();
                    string pG   = DR["PupilGender"].ToString();

                    //Rows containing a symbol mark score
                    if ((cN == "Level Code") && (aW2 != ""))
                    {
                        //Check to see if the dictionary contains the key, adds it if not
                        if(!subjectGradeCounts.ContainsKey(cSN + aW2))
                        {
                            subjectGradeCounts.Add(cSN+aW2, new 
                                Tuple<List<string>, List<string>>(new List<string>(), new 
                                List<string>()));
                        }

                        //Now that the key exists, if it didn't previously
                        //If male add to list 1, else list 2 (for female)
                        if(pG == "Male")
                        {
                            subjectGradeCounts[cSN + aW2].Item1.Add(pID);
                        }
                        else
                        {
                            subjectGradeCounts[cSN + aW2].Item2.Add(pID);
                        }
                    }
                }
            }
        }
    }

谢谢大家。

【问题讨论】:

  • 我要做的第一件事是检查字典是否已经包含您要添加的键,如果确实如此,您当前的代码将抛出异常,我将在下面添加我自己的示例尝试并防止异常。
  • 嗨,Ryan,我已经完成了,我将代码添加到主体中,谢谢。
  • 如果我必须为具有这种数据结构的项目做出贡献,我会问这是否真的有必要。似乎过于复杂。
  • 我不是 100% 确定你想要完成什么,但是我之前尝试过使用元组字典,并且总是因为没有使用类而自责。
  • 您还应该考虑将Tuple 替换为实际类。现在您正在创建一个 Tuple 并修改其中的值,但 Tuple 是不可变的,因此由于项目是 List 它可以工作,但如果您更改某些内容它将停止工作,这很令人困惑。

标签: c# .net


【解决方案1】:

在这里,我简化了您必须检查密钥是否存在的内容,如果不存在,则将其添加到新的初始化列表中,然后执行一个 if else for if male add to list 1 else (female) add to list 2,从你发布的代码这是我想出的

 foreach (DataRow DR in MainData.DataTable.Rows)
 {   
         //Rows containing a symbol mark score
         if ((DR["CN"].ToString() == "LC") && (DR["AW2"].ToString() != ""))
         {
            //Check to see if your dictionary contains the key, if not, add it
            if(!sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
            {
                 sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), new 
                 Tuple<List<string>,List<string>>(new List<string>(), new 
                 List<string>()));
            }

            //Now that the key exists, if it didn't previously
            //If male add to list 1, else list 2 (for female)
            if(DR["PG"].ToString() == "Male")
            {
                 sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item1.Add(DR["PupilID"].ToString());
            }
            else
            {
                 sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item2.Add(DR["PupilID"].ToString());
            }
        }
    }

【讨论】:

  • @JackClarke 据我所知,检查密钥是否存在,然后用新的初始化列表添加它是尽可能可靠的,但我确实提供了您当前代码的精简版本.
  • 非常感谢,太好了。我真的很感谢你的帮助。刚接触 C#,所以看到你更高效的类型代码真的很有帮助!
  • @JackClarke 很高兴我能帮上忙。
猜你喜欢
  • 2011-11-04
  • 1970-01-01
  • 2020-10-14
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2011-04-16
相关资源
最近更新 更多