【问题标题】:How do i delete an object from ILIST?如何从 ILIST 中删除对象?
【发布时间】:2021-05-29 23:20:40
【问题描述】:
class parent

    public string a;
    public string b;
    // child fields
    public string c;
    public string d;
    
    public parent(string a, string b)
    {  
        this.a = a;
        this.b = b;
    }


class child1 : parent
    {
     public child1(string a, string b, string c) :base(string a, string b)
    }

class child2 : parent
    {
     public child2(string a, string b, string d) :base(string a, string b)
    }

IList<parent> parent_list = new List<parent>();
parent_list.Add(new child1("243", "ewfwe", "fewf"));
parent_list.Add(new child2("456", "fewf", "efew"));
parent_list.Add(new child1("123", "efe", "ewfew"));
parent_list.Add(new child2("768", "fewf", "ewf"));

var foo = 123

我想删除以 123 作为字段 a 的对象的所有数据。 我似乎找不到执行此操作的正确方法。有可能吗?

【问题讨论】:

标签: c# oop


【解决方案1】:

是的,您可以应用此代码。

parent_list = parent_list.Where(item => item.a != "123").ToList();

更多详情请关注Where

【讨论】:

    【解决方案2】:

    在列表中倒数,边走边删除项目:

    for(var i = parent_list.Count - 1; i >= 0; i--)
        if(parent_list[i].a == "123")
            parent_list.Remove(i);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 2011-01-12
      • 1970-01-01
      • 2023-01-16
      • 2021-07-23
      • 2017-01-31
      相关资源
      最近更新 更多