代码之家  ›  专栏  ›  技术社区  ›  Thomas

对于每一个使用keyvaluepair ienumerable的索引用完?

c#
  •  -1
  • Thomas  · 技术社区  · 8 年前

    我遇到了一个奇怪的问题,我无法想象为什么。每当我使用foreach运行自定义填充的IENumerable KeyValuePair条目时,我都会得到一个错误: Index was out of range. Must be non-negative and less than the size of the collection. Prameter name: index

    代码:

    private void extractData(List<string> data)
    {
      IEnumerable<KeyValuePair<string, string>> extData;
      extData =
        data.Where((s, i) => i % 2 == 0)
        .Select((s, i) => 
            new KeyValuePair<string, string>(s, data.ElementAt(i * 2 + 1)));
    
      string extJournal = String.Empty;
      List<KeyValuePair> myData = new List<KeyValuePair>();
    
      foreach (KeyValuePair<string, string> keyValuePair in extData)
      {
          //1
         myData.Add(keyValuePair);
          //2
         extJournal+= string.Format("Metadata({0}): {1}{2}", 
              keyValuePair.Key, keyValuePair.Value, System.Environment.NewLine);
         //3
      }
    
    }
    

    错误似乎不是在数据集的分配过程中发生的,而是在foreach部分发生的(如果我将调试消息而不是//1-3,我将获得所有3个输出,但仍然会遇到一个直接指向foreach执行本身的错误的错误)。

    1 回复  |  直到 8 年前
        1
  •  3
  •   ikkentim    8 年前

    错误在您的 Where 选择器

    IEnumerable<KeyValuePair<string, string>> extData;
      extData =
        data.Where((s, i) => i % 2 == 0)
        .Select((s, i) => 
            new KeyValuePair<string, string>(s, data.ElementAt(i * 2 + 1)));
    

    i(2) % 2 将为0。在 Select

    更改 要包括的选择器 && i <= data.Count - 2

    迭代,而不是在定义查询时。