如何更改LINQ查询中的返回类型

发布于 2025-01-28 06:16:06 字数 884 浏览 2 评论 0原文

我正在寻找一种更改从返回类型的好方法 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 from
IEnumerable 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久夏青 2025-02-04 06:16:06

您投影到匿名类型,而不是元组,因此您不能从匿名类型的集合中投入到一组元组中。

最简单的修复程序是在选择中创建元组:

select (Category: g.Key, AveragePrice: g.Average(p => p.UnitPrice) )

那么您不需要铸造(返回类型已经是元组的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:

select (Category: g.Key, AveragePrice: g.Average(p => p.UnitPrice) )

Then you don't need a cast (the return type will already be an IEnumerable of your tuple)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文