问题描述
这是一个菜鸟问题 - 我对 C# 和泛型还很陌生,对谓词、委托和 lambda 表达式完全陌生...
This is a bit of noob question - I'm still fairly new to C# and generics and completely new to predicates, delegates and lambda expressions...
我有一个查询"类,其中包含另一个名为车辆"的类的通用列表.我正在构建代码以从父查询中添加/编辑/删除车辆.目前,我正在专门研究删除.
I have a class 'Enquiries' which contains a generic list of another class called 'Vehicles'. I'm building up the code to add/edit/delete Vehicles from the parent Enquiry. And at the moment, I'm specifically looking at deletions.
从我目前阅读的内容来看,我似乎可以使用 Vehicles.RemoveAll() 来删除具有特定 VehicleID 的项目或具有特定 EnquiryID 的所有项目.我的问题是理解如何提供 .RemoveAll 正确的谓词 - 我看到的示例过于简单(或者由于我缺乏谓词、委托和 lambda 表达式的知识,我可能过于简单了).
From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID or all items with a particular EnquiryID. My problem is understanding how to feed .RemoveAll the right predicate - the examples I have seen are too simplistic (or perhaps I am too simplistic given my lack of knowledge of predicates, delegates and lambda expressions).
所以,如果我有一个 List<Of Vehicle>车辆
,其中每个车辆都有一个 EnquiryID
,我将如何使用 Vehicles.RemoveAll()
删除给定 EnquiryID 的所有车辆?
So if I had a List<Of Vehicle> Vehicles
where each Vehicle had an EnquiryID
, how would I use Vehicles.RemoveAll()
to remove all vehicles for a given EnquiryID?
我知道有几种方法可以解决这个问题,所以我很想听听方法之间的区别 - 尽管我需要让某些东西发挥作用,但这也是一种学习练习.
I understand there are several approaches to this so I'd be keen to hear the differences between approaches - as much as I need to get something working, this is also a learning exercise.
作为补充问题,通用列表是这些对象的最佳存储库吗?我的第一个倾向是收藏,但似乎我已经过时了.当然泛型似乎是首选,但我对其他替代方案很好奇.
As an supplementary question, is a Generic list the best repository for these objects? My first inclination was towards a Collection, but it appears I am out of date. Certainly Generics seem to be preferred, but I'm curious as to other alternatives.
推荐答案
RemoveAll()
方法接受 Predicate
RemoveAll
将从集合中删除所有返回 True 且应用了谓词的 T
实例.
The RemoveAll()
methods accept a Predicate<T>
delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll
will remove from the collection all the T
instances that return True with the predicate applied.
C# 3.0 允许开发人员使用多种方法将谓词传递给 RemoveAll
方法(而不仅仅是这个……).你可以使用:
C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll
method (and not only this one…). You can use:
Lambda 表达式
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
匿名方法
vehicles.RemoveAll(delegate(Vehicle v) {
return v.EnquiryID == 123;
});
普通方法
vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
return v.EnquiryID == 123;
}
这篇关于List<object>.RemoveAll - 如何创建适当的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!