如何更改LINQ查询中的返回类型
我正在寻找一种更改从返回类型的好方法 iEnumerable
在anonymouStype中to ienumerable<(字符串类别,十进制平均值)>
/// <summary>
/// Gets the average price of each category's products.
/// </summary>
/// <returns>The average price of each category's products.</returns>
public static IEnumerable<(string Category, decimal averagePrice)> AveragePrice()
{
List<Product> products = GetListProducts();
var result = from p in products
group p by p.Category into g
select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
return (IEnumerable<(string Category, decimal averagePrice)>)result;
}
逻辑很好,但我的问题是如何在没有匿名功能的情况下接收相同的结果 - 我认为我应该将查询更改为产品列表的LINQ操作。我目前正在尝试使用铸造来做到这一点,但这无效,因为我的单元测试抛出了invalidcastException
。
我该如何正确执行?
I am searching for a good way to change the return type fromIEnumerable
in anonymousType to IEnumerable<(string Category, decimal averagePrice)>
/// <summary>
/// Gets the average price of each category's products.
/// </summary>
/// <returns>The average price of each category's products.</returns>
public static IEnumerable<(string Category, decimal averagePrice)> AveragePrice()
{
List<Product> products = GetListProducts();
var result = from p in products
group p by p.Category into g
select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
return (IEnumerable<(string Category, decimal averagePrice)>)result;
}
The logic is good but my problem is how to receive the same result without an anonymous function- I think I should change the query to a LINQ operation for products list. I am currently trying to do this with casting, but this doesn't work because my unit tests throw an InvalidCastException
.
How can I do this properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您投影到匿名类型,而不是元组,因此您不能从匿名类型的集合中投入到一组元组中。
最简单的修复程序是在选择中创建元组:
那么您不需要铸造(返回类型已经是元组的
iEnumerable
)You are projecting to an anonymous type, not a tuple, so you can't cast from a collection of anonymous types to a collection of tuples.
The easiest fix is to create tuples in your select:
Then you don't need a cast (the return type will already be an
IEnumerable
of your tuple)