C# 在泛型列表中搜索特定值
下面代码的目的是使用list.find方法在泛型列表中查找特定值。我正在粘贴下面的代码:C# 在泛型列表中搜索特定值,c#,generics,delegates,C#,Generics,Delegates,下面代码的目的是使用list.find方法在泛型列表中查找特定值。我正在粘贴下面的代码: class Program { public static List<Currency> FindItClass = new List<Currency>(); public class Currency { public string Country { get; set; } public string C
class Program
{
public static List<Currency> FindItClass = new List<Currency>();
public class Currency
{
public string Country { get; set; }
public string Code { get; set; }
}
public static void PopulateListWithClass(string country, string code)
{
Currency currency = new Currency();
currency.Country = country;
currency.Code = code;
FindItClass.Add(currency);
}
static void Main(string[] args)
{
PopulateListWithClass("America (United States of America), Dollars", "USD");
PopulateListWithClass("Germany, Euro", "EUR");
PopulateListWithClass("Switzerland, Francs", "CHF");
PopulateListWithClass("India, Rupees", "INR");
PopulateListWithClass("United Kingdom, Pounds", "GBP");
PopulateListWithClass("Canada, Dollars", "CAD");
PopulateListWithClass("Pakistan, Rupees", "PKR");
PopulateListWithClass("Turkey, New Lira", "TRY");
PopulateListWithClass("Russia, Rubles", "RUB");
PopulateListWithClass("United Arab Emirates, Dirhams", "AED");
Console.Write("Enter an UPPDERCASE 3 character currency code and then enter: ");
string searchFor = Console.ReadLine();
Currency result = FindItClass.Find(delegate(Currency cur) { return cur.Code == searchFor; });
Console.WriteLine();
if (result != null)
{
Console.WriteLine(searchFor + " represents " + result.Country);
}
else
{
Console.WriteLine("The currency code you entered was not found.");
}
Console.ReadLine();
}
}
列表是静态的,因为它位于一个小型控制台应用程序中。因为Main是静态的,所以它只能访问Program类中的静态变量,而不创建新的Program实例 static关键字表示整个程序中将有该变量的一个实例。通常,开发人员应该默认不使用静态变量,除非他们明确地确定他们想要一个变量实例 在comments状态下,调用Find时,现在可以选择使用delegate关键字。委托参数的目的是传递一个函数,该函数将针对列表中的每个项执行,以定位返回true的项 在现代C语言中,你可以这样写:
Currency result = FindItClass.Find(cur => cur.Code == searchFor);
为什么列表是静态的?这应该是本节目作者提出的一个问题。关于委托,这是因为Find需要一个谓词,其中T是列表的类型,所以您可以为它提供一个。不再需要delegate关键字。您可以编写:FindItClass.Findcur=>cur.Code==searchFor;您对为何使用委托进行查找有何想法?你有没有考虑过备选方案是什么?你想做什么?只需使用List.Find?我正在尝试在泛型列表中搜索特定值。我也很惊讶为什么这里会用到delegate。这就是为什么我首先问这样一个问题。
Currency result = FindItClass.Find(delegate(Currency cur) { return cur.Code == searchFor; });
Currency result = FindItClass.Find(cur => cur.Code == searchFor);