在列表中创建一个对象,删除并返回它

Die*_*ego 4 c# ienumerable list

可能重复:
c#:如何删除IEnumerable中的Item

我有一个无数的对象foo.

 public IEnumerable<foo> listOfFoo{ get; set; }
Run Code Online (Sandbox Code Playgroud)

Foo有Id和名字可以说.

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

这是最好的方式吗?

Raw*_*ing 5

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;
}
Run Code Online (Sandbox Code Playgroud)

哪个只是掩盖了匹配Foo?但是,"删除"的项目越多,性能越差越好.此外,任何其他引用的内容listOfFoo都不会发生任何变化.


Guf*_*ffa 4

对于任何实现IEnumerable<foo>. 例如,如果它是 a List<foo>,则可以为其删除项目,但如果它是例如 a ,foo[]则无法删除项目。

如果您使用 aList<foo>代替:

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