如何为 List中的 Find() 内容形成良好的谓词委托?
查看 MSDN 后,我仍然不清楚如何形成一个正确的谓词来使用 T 的成员变量(其中 T 是一个类)在 List 中使用 Find() 方法,
例如:
public class Car
{
public string Make;
public string Model;
public int Year;
}
{ // somewhere in my code
List<Car> carList = new List<Car>();
// ... code to add Cars ...
Car myCar = new Car();
// Find the first of each car made between 1980 and 2000
for (int x = 1980; x < 2000; x++)
{
myCar = carList.Find(byYear(x));
Console.Writeline(myCar.Make + myCar.Model);
}
}
我的“byYear”谓词应该是什么样子喜欢?
(MSDN 示例仅讨论恐龙列表,并且仅搜索不变的值“saurus”——它没有显示如何将值传递到谓词中...)
编辑:我正在使用 VS2005/.NET2 .0,所以我认为 Lambda 表示法对我来说不可用...
编辑2:删除了示例中的“1999”,因为我可能想根据不同的值以编程方式“查找”。 使用 for-do 循环将示例更改为从 1980 年到 2000 年的汽车系列。
After looking on MSDN, it's still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class)
For example:
public class Car
{
public string Make;
public string Model;
public int Year;
}
{ // somewhere in my code
List<Car> carList = new List<Car>();
// ... code to add Cars ...
Car myCar = new Car();
// Find the first of each car made between 1980 and 2000
for (int x = 1980; x < 2000; x++)
{
myCar = carList.Find(byYear(x));
Console.Writeline(myCar.Make + myCar.Model);
}
}
What should my "byYear" predicate look like?
(The MSDN example only talks about a List of dinosaurs and only searches for an unchanging value "saurus" -- It doesn't show how to pass a value into the predicate...)
EDIT: I'm using VS2005/.NET2.0, so I don't think Lambda notation is available to me...
EDIT2: Removed "1999" in the example because I may want to "Find" programatically based on different values. Example changed to range of cars from 1980 to 2000 using for-do loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 lambda 表达式,如下所示:
You can use a lambda expression as follows:
好的,在 .NET 2.0 中您可以使用委托,如下所示:
Ok, in .NET 2.0 you can use delegates, like so:
或者您可以使用匿名委托:
Or you can use an anonymous delegate:
由于您无法使用 lambda,因此您可以将其替换为匿名委托。
Since you can't use lambda you can just replace it with an anonymous delegate.
唔。 仔细考虑一下,您可以使用柯里化来返回谓词。
现在您可以将此函数的结果(这是一个谓词)传递给您的 Find 方法:
Hmm. Thinking more about it, you could use currying to return a predicate.
Now you can pass the result of this function (which is a predicate) to your Find method:
你也可以使用这个:
You can use this too: