Linq RemoveFirst 等效项
我正在寻找 Linq RemoveFirst(Predicate
但只能找到 RemoveAll
。
我知道我可以编写自己的扩展方法,但想知道是否已经存在具有不同名称的等效函数,或者是否有一种简单的方法来实现相同的结果。
I was looking for a Linq RemoveFirst(Predicate<T> match)
but could only find RemoveAll
.
I know I can write my own extension method but was wondering if there already exists an equivalent function with a different name, or an easy way to achieve the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样:
如果没有找到项目,就会抛出异常。
请注意,这与 LINQ 无关,只能使用
List
来完成。Like this:
If no item is found, an exception will be thrown.
Note that this has nothing to do with LINQ and can only be done with
List<T>
.这段代码实际上并没有从序列中“删除”元素,因为@SLaks 指出 linq 序列是只读的,但它确实跳过了满足条件的元素的第一次出现。它不是特别有效,因为每个列表操作都会迭代列表。它合理地表达了您想要实现的目标。根据您期望列表中包含的项目数量,这可能对您来说是合理的。
This code does not actually "remove" the element from the sequence since, as @SLaks points out linq sequences are readonly, but it does skip the first occurrence of the element that meets the criteria. It is not particularly efficient as each list operation is going to iterate over the list. It is reasonably expressive of what you are trying to accomplish. Depending on how many items you expect to have in your list, this might be reasonable for you.
由于没有其他人提供,这里是我的扩展方法/可枚举,它实现了RemoveFirst(Predicate match)。诀窍基本上是您需要定义自己的 IEnumerable 才能正确跟踪状态 - 我找不到解决这个问题的简单方法。
您可以在 此处的 .NET Fiddle 中尝试一下。
Since no one else has provided one, here's my extension method/enumerable that implements RemoveFirst(Predicate match). The trick is basically that you need to define your own IEnumerable to track the state properly--I couldn't find an easy way around that.
You can try it out in a .NET Fiddle here.
事实上,经典的List有一个RemoveAll(match),但没有一个RemoveFirst(match)。扩展方法可以是
Indeed the classic List has a RemoveAll(match) but not a RemoveFirst(match). An extension method could be