【问题标题】:remove list item based on index c#基于索引c#删除列表项
【发布时间】:2016-07-18 18:46:17
【问题描述】:

我有两个列表。 第一个列表包含字母和数字等值。 长度为 [0]-[36]。 第二个列表包含相似的值,长度也是 [0]-[36]。

我使用特定值迭代第二个列表两次以获取索引键,当我从第二个列表中获取索引键时,我想根据第二个列表中的索引删除第一个列表中的项目。

问题是第二次迭代不再起作用,因为第一个列表中的索引键已更改。

我可能应该将列表转换为数组(数组具有固定的索引键,列表在之后生成)但我不知道如何从数组中添加或删除索引键。

我不使用 Linq。

感谢您的帮助和建议 BR

代码示例:

List<int> list_z = new List<int>();
List<int> list_k = new List<int>();

for (int i = 0; i < second_list.Count; i++) {
    if (second_list[i] == "K")
    {
    list_k.Add(i);
    }
}

int k = list_k.Count; 

for (int i = 0; i < k; i++) {
    first_list.RemoveAt(list_k[i]);
}

for (int i = 0; i < second_list.Count; i++)
{
    if (second_list[i] == "Z")
    {
    list_z.Add(i);
    }
}

int z = list_z.Count;
for (int i = 0; i < svi_z; i++)
    first_list.RemoveAt(lista_z[i]); //here is error, because first_list doesnt have index key number 36 anymore
}

【问题讨论】:

  • 你会用字典吗?你在这里的目标是什么?我认为可能有一个更简单的解决方案。

标签: c# arrays list indexof


【解决方案1】:

根据索引从列表中删除项目时,您应该按降序删除它们(例如,您应该按此顺序删除第 11、8、3d、2 个项目)。在你的情况下:

  list_k.Sort();

  for (int i = list_k.Count - 1; i >= 0; --i)
    first_list.RemoveAt(list_k[i]);

【讨论】:

    【解决方案2】:

    有一个简单的解决方案可以从列表中逐个删除特定索引处的项目。即按降序排列索引,这样您就不会在列表中移动任何项目。

    例子:

    下面抛出错误:

    List<int> list = Enumerable.Range(0, 20).ToList();
    
    List<int> indexesToRemove = new List<int>(){ 5, 13, 18 };
    
    foreach(int i in indexesToRemove)
    {
        list.RemoveAt(i);
    }
    

    如果你这样做,你不会得到任何错误:

    List<int> list = Enumerable.Range(0, 20).ToList();
    
    List<int> indexesToRemove = new List<int>(){ 5, 13, 18 };
    
    foreach(int i in indexesToRemove.OrderByDescending(x => x))
    {
        list.RemoveAt(i);
    }
    

    所以在你的情况下,你只需要在循环之前调用list_z = list_z.OrderByDescending(x =&gt; x).ToList();,一切都会正常工作。

    或者,如果您不想使用 linq,您可以执行以下操作:

    list_z.Sort((x, y) => y - x);
    for (int i = 0; i < list_z.Count; i++)
        first_list.RemoveAt(lista_z[i]);
    }
    

    【讨论】:

      【解决方案3】:

      或者你可以简化你的工作:

              // Iterate and assign null
              for (var i = 0; i < second_list.Count(); i++)
              {
                  if (second_list[i] == "K")
                  {
                      first_list[i] = null;
                  }
              }
      
              // Iterate and assign null
              for (var i = 0; i < second_list.Count; i++)
              {
                  if (second_list[i] == "Z")
                  {
                      first_list[i] = null;
                  }
              }
      
              // remove nulls without linq or lambda
              first_list.RemoveAll(delegate (string o) { return o == null; });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-27
        • 2021-11-03
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多