如何将以下代码更改为秒类型:我尝试使用灵活的代码,例如first => second usage ...
第一种类型
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();
}
答案 0 :(得分:7)
您尚未声明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方法更不熟悉。