简体   繁体   English

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

[英]C# Remove object from list of objects

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 foreach but then realised you can't use this while modifying a collection, so I decided to use a normal for but then I'm not sure how to write code that does what I originally wrote. 最初,我使用了foreach但后来意识到在修改集合时不能使用此功能,因此我决定将Normal 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);
            }
        }

    }

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);

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);
    }
}

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

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

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()遍历该集合以创建要复制的副本:

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

There are two problems with this code: 此代码有两个问题:

  • Capacity represents the number of items the list can contain before resizing is required, not the actual count; Capacity表示需要调整大小之前列表可以包含的项目数,而不是实际数量。 you need to use Count instead, and 您需要改用Count ,并且
  • 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. 从列表中删除时,应向后移动,否则当两个相同的项目彼此相邻时,可以跳过第二个项目。

You're checking i 's UniqueID while i is actually an integer. i实际上是整数时,您正在检查iUniqueID You should do something like that, if you want to stay with a for loop. 如果要保留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);

First you have to find out the object in the list. 首先,您必须在列表中找到对象。 Then you can remove from the list. 然后,您可以从列表中删除。

       var item = myList.Find(x=>x.ItemName == obj.ItemName);
       myList.Remove(item);

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

You can use a while loop to delete item/items matching ChunkID. 您可以使用while循环删除与ChunkID匹配的项目。 Here is my suggestion: 这是我的建议:

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++;
      }
   }
}

Firstly, you are using Capacity instead of Count . 首先,您要使用Capacity而不是Count

Secondly, if you only need to delete one item, 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 all items 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);

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>来实现。)

foreach(object in objectList)
    {
       if (object.id == id)
       {
         // Remove item in objectList
           objectList.Remove(object);
       }
    }

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

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