如何从C#中的列表对象中删除项目 [英] How to remove items from list object in C#

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

问题描述

我有一些列表,只需要返回选定的项目。

除了剩余的必需值,所有需要从我的列表对象中删除。

我已编写代码如下所示,但收到此错误:

I have some list and needs to return only selected item.
except required values remaining all needs be removed from my list object.
for that i have written code like below but getting this error:

collection was modified enumeration operation





< b>我尝试了什么:





What I have tried:

class Program
{
    static void Main()
    {
        UserDetails obj = new UserDetails();
        obj.listUserDetails = obj.GetUserDetails();
        UserDetails obj1 = new UserDetails();
        string userIdentifier = "i3";
        foreach(var userDetail in obj.listUserDetails)
        {
            if (userDetail.Identifier != userIdentifier)
            {
                obj.listUserDetails.RemoveAll(a => a.Identifier != userIdentifier);
            }
        }
        foreach (var item in obj.listUserDetails)
        {
            Console.WriteLine(item.Identifier);
        }
        Console.Read();
    }
}
public class UserDetails
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string Identifier  { get; set; }
    public List<UserDetails> listUserDetails { get; set; }

    public List<UserDetails> GetUserDetails()
    {
        List<UserDetails> listUserDetails = new List<UserDetails>()
        {
            new UserDetails() { UserID=1,UserName="TestData",Identifier="i1"},
             new UserDetails() { UserID=2,UserName="TestData1",Identifier="i2"},
              new UserDetails() { UserID=3,UserName="TestData2",Identifier="i3"},
               new UserDetails() { UserID=4,UserName="TestData3",Identifier="i4"},
                new UserDetails() { UserID=5,UserName="TestData4",Identifier="i5"},
                 new UserDetails() { UserID=6,UserName="TestData5",Identifier="i6"},
        };
        return listUserDetails;
    }
  
}

推荐答案

Y在迭代时无法更改集合:if你想一想,你会明白为什么。如果你做了会怎么样?项目数量可能会发生变化,那么下一个项目会是什么?等等。



因此,要从集合中删除项目,请创建要删除的新项目集合,然后在处理完整个集合后将其全部删除。 br />


你可能也想读这个:列表与LT; T> - 它是否真的像您想象的那样高效? [ ^ ]
Y cannot change a collection while it s being iterated: if you think about it you'll realise why. What would happen if you did? The number of items could change, so which would be the "next" item? And so on.

So to delete items from a collection, create a new collection of items to delete, then remove them all after you have processed the whole collection.

You might also want to read this as well: List<T> - Is it really as efficient as you probably think?[^]


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

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