【问题标题】:Finding an object in a list, remove and return it [duplicate]在列表中查找对象,删除并返回它[重复]
【发布时间】:2012-09-20 02:58:45
【问题描述】:

可能重复:
c#: how do I remove an Item inside IEnumerable

我有无数对象foo

 public IEnumerable<foo> listOfFoo{ get; set; }

Foo 有 Id 和 name 让我们说。

我想将一个 ID 传递给一个方法,该方法应该从 IEnumerable 中删除具有该 ID 的对象并返回它。

最好的方法是什么?

【问题讨论】:

标签: c# list ienumerable


【解决方案1】:

IEnumerables 是只读的。您无法从中删除对象。

也就是说,你可以做类似的事情

public Foo QuoteRemoveUnquoteById(int id)
{
    var rtnFoo = listOfFoo.SingleOrDefault(f => f.Id == id);
    if (rtnFoo != default(Foo))
    {
        listOfFoo = listOfFoo.Where(f => f.Id != id);
    }
    return rtnFoo;
}

这只是掩盖了匹配的Foo?但是,您“删除”的项目越多,性能就会越来越差。此外,任何其他引用 listOfFoo 的东西都不会看到任何变化。

【讨论】:

    【解决方案2】:

    您不能简单地从 IEnumerable 中删除项目。


    但是您可以在基础集合中进行更改(例如,如果它是 List 或其他东西),或者使用 Where 子句过滤 IEnumerable

    如果你需要移除项目,你应该使用支持移除项目的集合,比如List&lt;&gt;


    例如,您可以将支持字段的类型设为List&lt;foo&gt;

    private List<foo> _listOfFoo;
    
    public IEnumerable<foo> listOfFoo 
    { 
        get { return _listOfFoo.AsReadOnly(); } 
        set { _listOfFoo = value.ToList(); } 
    }
    

    然后从_listOfFoo 中删除项目。

    _listOfFoo.Remove(_listOfFoo.Single(foo => foo.ID == id_to_remove));
    

    【讨论】:

      【解决方案3】:

      IEnumarable 是一个用于遍历集合的接口,如果不强制转换为某种集合,就无法删除项目。

      在这里阅读更多:

      http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

      【讨论】:

        【解决方案4】:

        这对于任何实现IEnumerable&lt;foo&gt; 的集合都是不可能的。如果是 List&lt;foo&gt;,则可以为其删除项目,但如果是 foo[],则无法删除项目。

        如果您改用List&lt;foo&gt;

        public foo Extract(int id) {
          int index = listOfFoo.FindIndex(x => x.Id == id);
          foo result = listOfFoo[index];
          listOfFoo.removeAt(index);
          return result;
        }
        

        【讨论】:

        • 谢谢,我已经使用你的方法了。我不认为使用数组索引有问题,对吧?
        猜你喜欢
        • 2021-02-02
        • 1970-01-01
        • 2020-12-19
        • 2010-10-19
        • 1970-01-01
        • 1970-01-01
        • 2016-05-28
        • 2017-02-02
        • 1970-01-01
        相关资源
        最近更新 更多