我该如何形成良好的谓词委托查找我的名单,LT()的东西; T> ;? [英] How do I form a good predicate delegate to Find() something in my List<T>?
问题描述
看MSDN上后,它仍然是我不清楚,我应该如何使用T(其中T是一个类)
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)
例如:
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谓词是什么样子?
What should my "byYear" predicate look like?
(MSDN的例子只恐龙,只有搜索的列表会谈的一个不变的值saurus - 它不显示怎么传值到谓词...)
(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...)
编辑:我使用VS2005 / .NET2.0,所以我不认为LAMBDA符号是提供给我...
I'm using VS2005/.NET2.0, so I don't think Lambda notation is available to me...
EDIT2:在这个例子中删除了1999,因为我可能要查找编程基于不同的价值观。例如使用-do循环改为汽车的范围一九八〇年至2000年。
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.
推荐答案
好吧,在.NET 2.0中,您可以使用代表,像这样:
Ok, in .NET 2.0 you can use delegates, like so:
static Predicate<Car> ByYear(int year)
{
return delegate(Car car)
{
return car.Year == year;
};
}
static void Main(string[] args)
{
// yeah, this bit is C# 3.0, but ignore it - it's just setting up the list.
List<Car> list = new List<Car>
{
new Car { Year = 1940 },
new Car { Year = 1965 },
new Car { Year = 1973 },
new Car { Year = 1999 }
};
var car99 = list.Find(ByYear(1999));
var car65 = list.Find(ByYear(1965));
Console.WriteLine(car99.Year);
Console.WriteLine(car65.Year);
}
这篇关于我该如何形成良好的谓词委托查找我的名单,LT()的东西; T> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!