[英]How to change return type in LINQ query
我正在尋找一種將返回類型從 anonymousType 中的IEnumerable
更改為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;
}
邏輯很好,但我的問題是如何在沒有匿名函數的情況下接收相同的結果 - 我認為我應該將查詢更改為產品列表的 LINQ 操作。 我目前正在嘗試通過強制轉換來做到這一點,但這不起作用,因為我的單元測試拋出了InvalidCastException
。
我怎樣才能正確地做到這一點?
您正在投影到匿名類型,而不是元組,因此您不能從匿名類型集合轉換為元組集合。
最簡單的解決方法是在您的選擇中創建元組:
select (Category: g.Key, AveragePrice: g.Average(p => p.UnitPrice) )
然后你不需要強制轉換(返回類型已經是你的元組的IEnumerable
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.