如何为var添加值myDictionary = new Dictionary()

本文关键字:int Values Dictionary new var 添加 myDictionary | 更新日期: 2023-09-27 18:15:25

我创建了一个包含public string value1public string value2public struct Values

public struct Values
{
   public string header;
   public string type;
}

我的字典:

var myDictionary = new Dictionary<int, Values>();

问题:如何为每个键添加两个值?

while (true)
{
   for (int i = 0; i < end i++)
   {
        myDictionary.Add(i, value1 , value2);
   }
}

如何为var添加值myDictionary = new Dictionary<int, Values>()

如果您想生成字典,您可以尝试使用Linq:

 var myDictionary = Enumerable 
   .Range(0, end)
   .Select(i => new {
      key = i,
      value = new Values() {
        header = HeaderFromIndex(i), //TODO: implement this
        type = TypeFromIndex(i)      //TODO: implement this 
      }})
   .ToDictionary(item => item.key, item => item.value);

如果你想添加条目到现有的字典:

 for (int i = 0; i < end; ++i)
   myDictionary.Add(i, new Values() {
     header = HeaderFromIndex(i), //TODO: implement this
     type = TypeFromIndex(i)      //TODO: implement this 
   }); 

请注意,在任何情况下字典都包含: {key, value};因此,如果您想要两个项作为对应键的值,您必须值组织到一个类new Values() {header = ..., type = ...}中,在您的情况下

如果我得到正确的问题,您必须初始化一个Values对象,然后将其添加到您的字典中。这样的:

while (true) {
    for (int i = 0; i < end i++) {
        Values tmp_values;
        tmp_values.header = "blabla";
        tmp_values.type = "blabla type";
        myDictionary.Add(i, tmp_values);
    }
}