1
我怎样才能改变下列代码进行第二式:我尝试使用flexable码像第一=>第二次使用...如何在linq中使用Func <Tkey,T>?
第一种类型
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();
}
你能解释一下吗?“请注意,如果真的那么简单,我个人宁愿自己调用Select()和ToList()。额外的方法并没有节省太多,对大多数开发人员来说,标准的LINQ方法“。 – Penguen 2010-08-15 17:57:23
@Phsika:'GetSource'方法实际上不会直接通过调用'Select'来购买你。 – 2010-08-15 17:58:25
你是否建议我上面的Jon Skeet解决方案所需的代码? – Penguen 2010-08-15 18:00:40