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();
}
You haven’t declared what
TKeyis – you need to make that another generic type parameter for the method: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:
Mind you, if it’s really that simple I’d personally rather just call
Select()andToList()myself. The extra method isn’t saving much, and it will be less familiar to most developers than the standard LINQ methods.