【问题标题】:Create a new list when I have new key while adding to Dictionary in a loop当我在循环中添加到字典时有新键时创建一个新列表
【发布时间】:2016-02-07 19:35:13
【问题描述】:

我正在尝试逐行迭代读取数据的文件。阅读后我想存储在字典中。键是唯一的,但值具有键的值列表(每个键可能有 50 个值)。但是,当迭代键随机出现时。如何为每个键创建一个新列表并将值存储在相应的列表中,当下次相同的键出现时......如何将所有这些新键和相应的列表存储在字典中。请告诉我..

这是我的代码的解释..

Dictionary<String,List<PropertyCollection>> dict = new Dictionary<String,List<PropertyCollection>>(); 

List<String> list1 = new List<String>();  

//Here I am iterating the each record and getting the type and id  

for (i=1;i<datarr.length -1;i++){  

String type = datarr[3].Trim();  

String id = datarr[1].Trim();  

//here I am checking the key in map adding   

if(dict.ContainsKey(type)){  

//I need help here if the key is not there create a new record with key as "type" and values  as "id"s. All the values of same type should add in a list.If any new type comes in iteration it should add as new entry and having key and values are Ids in a list format.  


I stuck here ..


}  

}  

我不知道该文件中有多少“类型”。所以我需要动态构建列表。

Please help . 

【问题讨论】:

  • 你试过了吗?
  • 如果你至少要尝试一些东西,这实际上很容易完成..现在来吧
  • 我已经尝试了一些东西。我会在这里更新我的代码

标签: c# collections


【解决方案1】:

在使用值为集合的Dictionary 时,这是一个非常常见的场景。在尝试向其中添加任何内容之前,您只需要确保该集合已针对该键进行了初始化:

//using Dictionary<int, List<string>>
for(int i in ...)
{
   if (!dict.ContainsKey(i))
      dict[i] = new List<string>();

   dict[i].Add("hello");
}

现在每一个新的密钥都会得到一个新的List&lt;string&gt;

【讨论】:

  • 感谢您的回答但可能这是主要问题.. 我不知道之前有多少个键。和键是字符串格式。
  • 感谢您的回答但可能这是主要问题.. 我不知道之前有多少个键。和键是字符串格式。如果可能的话,请您举一个完整的例子。我对.net 很陌生。假设键是花,我需要将与花相关的 ID 添加到我正在阅读的文件中的列表中。如果关键是食物,我需要从文件中添加与食物相关的 ID
【解决方案2】:

构建数据的类:

class DataBuilder
{
    public Dictionary<string, List<string>> Data { get; } = new Dictionary<string, List<string>>();

    public void Add(string key, string dataVal)
    {
        if (!Data.ContainsKey(key))
        {
            Data.Add(key, new BaseList<string>());
        }

        Data[key].Add(dataVal);
    }
}

这是您在读取文件时如何使用上述类来构建数据的方法:

static void Main(string[] args)
    {
        var builder = new DataBuilder();

        builder.Add("Key1", "Test Data 1");
        builder.Add("Key1", "Test Data 2");
        builder.Add("Key2", "Test Data 3");
        builder.Add("Key1", "Test Data 4");            
    }

根据您的查询更新:将您的代码更改为:

private void Process()
    {

        Dictionary<String, List<string>> dict = new Dictionary<String, List<string>>();

        for (int i = 0; i < numOfRec - 1; i++)
        {
            //Code to Read record at index i into dataarr.

            String type = datarr[3].Trim();

            String id = datarr[1].Trim();

            if (!dict.ContainsKey(type))
            {
                dict.Add(type, new BaseList<string>());
            }

            dict[type].Add(id);
        }
    }
}

【讨论】:

  • 我已经更新了我的问题,请看一次。
  • 我的解决方案仍然适用于您的问题。请参阅上面的更新。
猜你喜欢
  • 2021-12-14
  • 2019-08-25
  • 2017-07-18
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2019-09-17
相关资源
最近更新 更多