C# 从对象列表中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18917725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:35:23  来源:igfitidea点击:

C# Remove object from list of objects

c#

提问by user9993

I have a list of objects and I am trying to remove a specific object in the list by first checking a property in the object.

我有一个对象列表,我试图通过首先检查对象中的属性来删除列表中的特定对象。

Originally I used a foreachbut then realised you can't use this while modifying a collection, so I decided to use a normal forbut then I'm not sure how to write code that does what I originally wrote.

最初我使用了 aforeach但后来意识到你不能在修改集合时使用它,所以我决定使用普通for但后来我不确定如何编写代码来完成我最初编写的代码。

How do I go about writing code to do what I originally had?

我该如何编写代码来完成我最初的工作?

Thanks

谢谢

Here's my code:

这是我的代码:

    public void DeleteChunk(int ChunkID)
    {
        //foreach (Chunk i in ChunkList)
        //{
        //    if (i.UniqueID == ChunkID)
        //    {
        //        ChunkList.Remove(i);
        //    }
        //}

        //This won't work because here i is just an integer so i.UniqueID won't exist.
        for (int i = 0; i < ChunkList.Capacity; i++)
        {
            if (i.UniqueID == ChunkID)
            {
                ChunkList.Remove(i);
            }
        }

    }

回答by Khan

You can simplify this with linq:

您可以使用 linq 简化此操作:

var item = ChunkList.SingleOrDefault(x => x.UniqueId == ChunkID);
if (item != null)
    ChunkList.Remove(item);

You can also do the following, which will also work if there is more than one match:

您还可以执行以下操作,如果存在多个匹配项,这也将起作用:

ChunkList.RemoveAll(x => x.UniqueId == ChunkID);

回答by bland

You're removing and then incrementing, which means you'll be one ahead of yourself. Instead, remove in reverse so you never mess up your next item.

您正在删除然后递增,这意味着您将领先于自己。相反,反向删除,这样你就不会弄乱你的下一个项目。

for (int i = ChunkList.Count-1; i >=0; i--)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.RemoveAt(i);
    }
}

回答by bland

One technique is to create a copy of the collection you want to modify, change the copy as needed, then replace the original collection with the copy at the end.

一种技术是创建要修改的集合的副本,根据需要更改副本,然后用最后的副本替换原始集合。

回答by dasblinkenlight

There are two problems with this code:

这段代码有两个问题:

  • Capacityrepresents the number of items the list can contain before resizing is required, not the actual count; you need to use Countinstead, and
  • When you remove from the list, you should go backwards, otherwise you could skip the second item when two identical items are next to each other.
  • Capacity表示在需要调整大小之前列表可以包含的项目数,而不是实际数量;你需要Count改用,并且
  • 当您从列表中删除时,您应该向后退,否则当两个相同的项目彼此相邻时,您可以跳过第二个项目。

回答by Moo-Juice

If ChunkListis List<Chunk>, you can use the RemoveAllmethod:

如果ChunkListList<Chunk>,则可以使用以下RemoveAll方法:

ChunkList.RemoveAll(chunk => chunk.UniqueID == ChunkID);

回答by Raz Harush

You're checking i's UniqueIDwhile iis actually an integer. You should do something like that, if you want to stay with a forloop.

您正在检查i's UniqueIDwhilei实际上是一个整数。如果你想保持for循环,你应该做类似的事情。

for (int i = 0; i < ChunkList.Capacity; i++)
{
    if (ChunkList[i].UniqueID == ChunkID)
    {
        ChunkList.Remove(i);
    }
}

You can, and should, however, use linq:

但是,您可以并且应该使用 linq:

ChunkList.Remove(x => x.UniqueID == ChunkID);

回答by DGibbs

Originally I used a foreach but then realised you can't use this while modifying a collection

最初我使用了 foreach 但后来意识到你不能在修改集合时使用它

You can create a copy of the collection and iterate over that using ToList()to create to copy:

您可以创建集合的副本并使用ToList()create to copy 对其进行迭代:

 foreach(Chunk chunk in ChunkList.ToList())
 {
     if (chunk.UniqueID == ChunkID)
     {
         ChunkList.Remove(chunk);
     }
 }

回答by Matthew Watson

Firstly, you are using Capacityinstead of Count.

首先,您使用的是Capacity代替Count.

Secondly, if you onlyneed to delete oneitem, then you can happily use a loop. You just need to ensure that you break out of the loop after deleting an item, like so:

其次,如果你需要删除一项,那么你可以愉快地使用循环。您只需要确保在删除项目后跳出循环,如下所示:

int target = 4;

for (int i = 0; i < list.Count; ++i)
{
    if (list[i].UniqueID == target)
    {
        list.RemoveAt(i);
        break;
    }
}

If you want to remove allitems from the list that match an ID, it becomes even easier because you can use List<T>.RemoveAll(Predicate<T> match)

如果您想从列表中删除与 ID 匹配的所有项目,则变得更加容易,因为您可以使用List<T>.RemoveAll(Predicate<T> match)

int target = 4;

list.RemoveAll(element => element.UniqueID == target);

回答by knguyen

You can use a while loop to delete item/items matching ChunkID. Here is my suggestion:

您可以使用 while 循环删除与 ChunkID 匹配的项目。这是我的建议:

public void DeleteChunk(int ChunkID)
{
   int i = 0;
   while (i < ChunkList.Count) 
   {
      Chunk currentChunk = ChunkList[i];
      if (currentChunk.UniqueID == ChunkID) {
         ChunkList.RemoveAt(i);
      }
      else {
        i++;
      }
   }
}

回答by knocte

Simplest solution without using LINQ:

不使用 LINQ 的最简单解决方案:

    Chunk toRemove = null;
    foreach (Chunk i in ChunkList)
    {
        if (i.UniqueID == ChunkID)
        {
            toRemove = i;
            break;
        }
    }
    if (toRemove != null) {
        ChunkList.Remove(toRemove);
    }

(If Chunk is a struct, then you can use Nullable<Chunk> to achieve this.)

(如果 Chunk 是一个结构体,那么您可以使用 Nullable<Chunk> 来实现这一点。)