我正在尝试逐行迭代读取数据的文件。看完之后我想存放在词典中。键是唯一的,但值具有键的值列表(每个键可以是50个值)。但是迭代键随机出现。如何为每个键创建一个新列表,并在下次相同的键出现时将值存储在相应的List中...如何将所有这些新键和相应的列表存储在字典中。请告诉我这个..
这是我的代码的解释..
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 ..
}
}
我不知道有多少&#34;类型&#34;在那个文件中。所以我需要动态构建List。
Please help .
答案 0 :(得分:0)
当使用值为集合的Dictionary
时,这是一种非常常见的情况。在尝试向其添加任何内容之前,您只需确保为该密钥初始化集合:
//using Dictionary<int, List<string>>
for(int i in ...)
{
if (!dict.ContainsKey(i))
dict[i] = new List<string>();
dict[i].Add("hello");
}
现在,每一个新密钥都将获得新的List<string>
答案 1 :(得分:0)
构建数据的类:
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);
}
}
}