'How to change return type in LINQ query

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?



Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1