[英]How to store result of a LINQ statement executed in foreach to a variable for future use?
[英]LINQ - Creating a Property to Store the Result of a LINQ statement
我有一個用C#編寫的應用程序。 在這個應用程序中,我有一些代碼在兩個數據源之間連接一些數據。 該代碼如下所示:
Result result = new Result();
var items = from userOrder in UserOrders
join product in UserProducts on userOrder.OrderId equals prodcut.OrderId
orderby userOrder.Date, product.Name
select new
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
result.Items = items.ToList();
代碼的最后一行創建了一個編譯時錯誤,該錯誤表示:
Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: DateTime OrderDate, string ProductName>>' to 'System.Collections.Generic.List<dynamic>'
當此錯誤通信時,我的Result
對象上的Items
屬性當前是List<dynamic>
。 我可以改變這個屬性的類型。 但是,我需要這個屬性,以便我可以遍歷我的報告中的Items
。 我的問題是, Items
應該是什么類型的財產?
您正在使用此行將此列表強制轉換為匿名對象:
select new
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
嘗試在New之后添加result.Items的類型:
select new TYPE
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
編輯:看起來物品的類型可能是動態列表? 您應該為這些創建一個硬類型。 您混合動態和匿名對象。
你可以這樣做:
result.Items = ((IEnumberable<dynamic>)items).ToList();
但我通常建議只使用硬類型,因為你獲得了編譯類型檢查,並且沒有像你在這里遇到的錯誤。
Edit2:這是一個我的意思是'硬類型'的例子
public class UserOrderProduct
{
public DateTime OrderDate { get; set; }
public string ProductName { get; set; }
}
現在最后的選擇將是:
select new UserOrderProduct
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
並且不要忘記更改result.Items的類型:
List<UserOrderProduct>
為什么它不起作用
您正在嘗試將對象分配給result.Items與定義的類型不匹配。 result.Items是動態的,你正在為它分配一個匿名類型。
怎么修
只需創建一個類來保存聚合數據的結果。
public class OrderDetailsSummary
{
public DateTime OrderDate { get; set; }
public string ProductName { get; set; }
}
更改您的Linq查詢以使用它。
select new OrderDetailsSummary
{
OrderDate = userOrder.Date,
ProductName = product.Name,
};
將Result類的Items屬性更改為OrderDetailsSummary類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.