C#从对象列表中删除对象 [英] C# Remove object from list of objects

查看:149
本文介绍了C#从对象列表中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

最初,我使用了 foreach ,但是后来意识到您不能在修改集合时使用它,所以我决定使用普通的 for ,但后来我没有使用确定如何编写与我最初编写的代码相同的代码.

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.

我该如何编写代码以完成原来的工作?

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

谢谢

这是我的代码:

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

    }

推荐答案

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

You can simplify this with 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);

这篇关于C#从对象列表中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆