gpt4 book ai didi

c# - 如何在 linq 中使用 Func

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:01 25 4
gpt4 key购买 nike

我如何将以下代码更改为第二种类型:我尝试使用灵活的代码,如第一种 => 第二种用法...

第一种类型



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 方法。

关于c# - 如何在 linq 中使用 Func<Tkey,T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3488481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com