我如何将以下代码更改为第二种类型:我尝试使用灵活的代码,如第一种 => 第二种用法...
第一种类型
private void Form1_Load(object sender, EventArgs e)
{
List<City> cities = new List<City>
{
new City{ Name = "Sydney", Country = "Australia" },
new City{ Name = "New York", Country = "USA" },
new City{ Name = "Paris", Country = "France" },
new City{ Name = "Milan", Country = "Spain" },
new City{ Name = "Melbourne", Country = "Australia" },
new City{ Name = "Auckland", Country = "New Zealand" },
new City{ Name = "Tokyo", Country = "Japan" },
new City{ Name = "New Delhi", Country = "India" },
new City{ Name = "Hobart", Country = "Australia" }
};
List<string> mylistName = GetData(cities, c => c.Name);
foreach (string item in mylistName)
{
listBox1.Items.Add(item);
}
List<string> mylistCountry = GetData(cities, c => c.Country);
foreach (string item in mylistCountry)
{
listBox2.Items.Add(item);
}
}
public List<T> GetData<T>(List<City> cities, Func<City, T> selector)
{
return cities.Select(selector).ToList();
}
}
public class City
{
public string Name { get; set; }
public string Country { get; set; }
}
第二种我需要以下内容:
public List<T> GetData<T>(List<Tkey> cities, Func<Tkey, T> selector)
{
return cities.Select(selector).ToList();
}
您还没有声明什么是 TKey
- 您需要为该方法创建另一个泛型类型参数:
public List<T> GetData<TKey, T>(List<TKey> cities, Func<TKey, T> selector)
{
return cities.Select(selector).ToList();
}
但是,如果您有多个类型参数,我强烈建议您为它们提供所有“完整”名称。例如,我会使用:
public List<TResult> GetData<TSource, TResult>(List<TSource> cities,
Func<TSource, TResult> selector)
{
return cities.Select(selector).ToList();
}
请注意,如果真的那么简单,我个人宁愿自己调用 Select()
和 ToList()
。额外的方法并没有节省多少,而且大多数开发人员对它的熟悉程度不如标准的 LINQ 方法。
我是一名优秀的程序员,十分优秀!