Reputation: 17288
How can i change below codes to second Type: i try to use flexable codes like first =>second usage...
First Type
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; }
}
Second Type i need below:
public List<T> GetData<T>(List<Tkey> cities, Func<Tkey, T> selector)
{
return cities.Select(selector).ToList();
}
Upvotes: 1
Views: 1525
Reputation: 1501163
You haven't declared what TKey
is - you need to make that another generic type parameter for the method:
public List<T> GetData<TKey, T>(List<TKey> cities, Func<TKey, T> selector)
{
return cities.Select(selector).ToList();
}
However, I would strongly recommend that if you have more than one type parameter, you give them all "full" names. For example, I'd use:
public List<TResult> GetData<TSource, TResult>(List<TSource> cities,
Func<TSource, TResult> selector)
{
return cities.Select(selector).ToList();
}
Mind you, if it's really that simple I'd personally rather just call Select()
and ToList()
myself. The extra method isn't saving much, and it will be less familiar to most developers than the standard LINQ methods.
Upvotes: 7