【问题标题】:How to insert an list one by one(Looping over forl loop) to a dictionary of list in c#如何将一个列表一个一个地插入(循环for循环)到c#中的列表字典中
【发布时间】:2016-09-13 14:46:25
【问题描述】:

我正在循环列表并在 c# 中附加列表的字典,但它只附加了 forloop 的最后一个值

class Crawl
{
    public void SomeFunction()
    {
        string[] arr1 = new string[] { "one", "two", "three" };
        var variations_hash = new Dictionary<string, List<string>>();
        foreach(var item1 in arr1)
        {
            variations_hash["v_id_1"] = item1;
        }
        foreach (var job in variations_hash) 
        {
            foreach (string jobs in job.Value) 
            {
                Console.Write (jobs+"\n");
            }
        }
    }
    . . .
}

结果:

three

预期结果:

one
two
three

如何将所有 for 循环值一一(作为列表/数组)附加到字典(variations_hash)

预期结构将是

{"v_id_1":"["one","two","three"]"}

【问题讨论】:

  • 这甚至不应该编译,因为 item1string 并且 variations_hash["v_id_1"] 期待 List&lt;string&gt;
  • @juharr:arr1 是数组。 item1foreach 将来自 arr1 的枚举器的每个返回分配给的字符串。
  • @AlexGravely 是的,我知道。这是variations_hash["v_id_1"] = item1; 无法编译的原因,因为它将string 分配给List&lt;string&gt;
  • @juharr:哎呀,我不知道为什么我认为它是在迭代键,而不是值。我需要我的早晨 Pepper 博士。
  • @AlexGravely HA,我已经有了我的;)

标签: c# arrays list dictionary hash


【解决方案1】:

你应该

  1. 如果键不存在,则添加新的键值对
  2. 如果键存在,则将新项目添加到相应的

让我们看看应该发生什么:

  1. item1"one",有 no"v_id_1" 所以我们添加一对:{"v_id_1", ["one"]};
  2. item1"two"一个键 "v_id_1",我们添加到 对应的值 {"v_id_1", ["one", "two"]};
  3. 最后,item1"three" 有一个键 "v_id_1",我们再次添加到 对应值 {"v_id_1", ["one", "two", "three"]}

实现可能是这样的:

string[] arr1 = new string[] { "one", "two", "three" };
var variations_hash = new Dictionary<string, List<string>>();

foreach(var item1 in arr1) { 
  List<String> list; 

  if (variations_hash.TryGetValue("v_id_1", out list))
    list.Add(item1);
  else
    variations_hash.Add("v_id_1", new List<String>() {item1}); 
}
...

【讨论】:

    【解决方案2】:

    您只需将整个数组分配给字典,而不是循环遍历它。

    variations_hash["v_id_1"] = arr1.ToList();
    

    【讨论】:

    • 但是我怎样才能自动化更大的数据呢?
    • 你必须展示你在说什么。根据您发布的问题/代码,这可以解决您的问题。
    • 抱歉,这是最初的问题“如何逐个附加所有 for 循环值”
    【解决方案3】:

    与其给你一个工作代码示例,我想我只是为你指出正确的方向。

    由于您想要一个以列表为值的字典,因此以相反的顺序思考会更容易。尝试先准备好您的列表,然后在最后将该列表添加到字典中。

    您应该注意到您一直在使用单个项目重置 Dictionary 的值。由于字典是通用的,它不知道您要将新值附加到当前存在的值上。这就是为什么我发现向后工作更容易,然后它应该很容易就位。

    【讨论】:

      【解决方案4】:

      第一个foreach 是您的问题,您将 v_id_1 的值设置了三次,而不是添加所有三个值,尝试:

      string[] arr1 = new string[] { "one", "two", "three" };
      var variations_hash = new Dictionary<string, List<string>>();
      variations_hash["v_id_1"] = arr1.ToList();
      foreach (var job in variations_hash)
      {
          foreach (string jobs in job.Value)
          {
              Console.Write(jobs + "\n");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-04
        • 2022-01-06
        • 1970-01-01
        • 2013-07-20
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 2019-11-02
        相关资源
        最近更新 更多