简体   繁体   English

从列表中删除元素

[英]Remove elements from a list

I have a list and I would like to remove some elements from it. 我有一个列表,我想从中删除一些元素。

Problem I ran into is that If I want to remove more than one element, then I lose control of what I'm removing. 我遇到的问题是,如果要删除多个元素,那么我将失去对要删除内容的控制。

See, the code `mylist.Removeat(index) does the work just fine, however, if I have a list o let's say 10 elements and I need to remove 6 randomly, I don't seem to find a function that removes them all at once, instead, it removes the first element, then the second and so on and it is not really what I want. 看,代码`mylist.Removeat(index)可以很好地工作,但是,如果我有一个列表,比如说有10个元素,而我需要随机删除6个元素,那么我似乎没有找到可以将它们全部删除的函数而是一次删除了第一个元素,然后删除了第二个元素,依此类推,这并不是我真正想要的。

Thanks, 谢谢,

EDIT: 编辑:

Thanks all for your comments, the best way was doing a loop descending like this: 谢谢大家的评论,最好的方法是像这样循环下降:

            int img_count = img.Count;

            for (int i = img_count; i >0; --i)
            {
                if (images_to_delete.Contains(i)) img.RemoveAt(i);
            }

I think your problem is that once you delete an item at a certain index, all the other indexes shift. 我认为您的问题是,一旦删除某个索引处的项目,所有其他索引都会转移。 Like if you had an array of {"a", "b", "c"} , and wanted to remove a and b by passing in indexes = [0,1] . 就像您有{"a", "b", "c"}的数组一样,并且想要通过传递indexes = [0,1]来删除ab Once you call removeAt(0) , now "b" is at index 0. 一旦调用removeAt(0) ,现在“ b”的索引为0。

One way to handle it is to notice the fact that only higher indexes get shifted. 处理该问题的一种方法是注意到只有较高的索引会移位的事实。 So if you remove the 5th element for example, 0-4 are still going to have the same meaning; 因此,例如,如果删除第5个元素,则0-4仍然具有相同的含义; only 5 and up are affected. 仅5岁及以上受到影响。

Because of this, you can just remove the indexes in descending order (highest to lowest)! 因此,您可以按降序删除索引(从最高到最低)! For example: 例如:

var vals = new[]{ "a", "b", "c" };
RemoveMultiple(vals, 0, 1);

and then RemoveMultiple looks like this: 然后RemoveMultiple看起来像这样:

public void RemoveMultiple<T>(List<T> list, params int[] indexes)
{
   // if this next line gives you a compiler error, you need to include
   // linq by putting a "using System.Linq;" at the very top of the file.
   var sortedIndexes = indexes.OrderByDescending(i => i);
   foreach(var indexToRemove in sortedIndexes)
   {
      list.RemoveAt(indexToRemove);
   }
}

That should work! 那应该工作!

The question isn't extremely clear, but if you want to remove a specified number of elements at random indexes from the List here is a method that will do that. 这个问题不是很清楚,但是如果您想从列表中的随机索引中删除指定数量的元素,可以使用此方法。 (This is example is with a list of String objects, but you could change it to use any object of course). (这是一个String对象列表的示例,但是您可以更改它以使用任何对象)。

private static List<String> strList = new List<String>();        
        static void Main(string[] args)
        {
            strList.AddRange("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(','));
            removeRandomItemsFromList(strList, 8);
            Console.WriteLine(String.Join(",",strList.ToArray()));
            Console.ReadLine();
        }

        private static void removeRandomItemsFromList(List<String> list, int numToRemove){
            Random randGenerator = new Random();
            if(numToRemove >= list.Count()){
                Console.WriteLine("Num to remove is as big or larger than list size, clearing list.");
                list.Clear();
                return;                
            }

            for (int i = 0; i < numToRemove; i++)
            {
                int randIndex = randGenerator.Next(list.Count - 1); //get random index within bounds of list
                list.RemoveAt(randIndex);
            }
        }

When I ran it I got the output: B,C,F,H,I,J,K,M,N,O,P,Q,R,U,V,X,Y,Z 当我运行它时,我得到输出:B,C,F,H,I,J,K,M,N,O,P,Q,R,U,V,X,Y,Z
But of course it will usually be different since it's removing random items. 但是当然,由于它会删除随机项目,因此通常会有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM