[英]Flattened records to parent/child objects using LINQ. Without duplication of data
我正在嘗試使用 LINQ 更好地理解分組。 我想收集一組扁平記錄並將它們轉換為父/子關系中的兩個對象集合。 在我的示例中,扁平記錄包含在 ImportedExpenses 類中,而 Expense/ExpenseLineItem 類分別形成父/子關系。
public class ImportedExpense {
public string EmployeeName {get; set;}
public string CustomerName {get; set;}
public DateTime ExpenseDate {get; set;}
public Decimal Amount {get; set;}
public string Description {get; set;}
}
public class Expense {
public string EmployeeName {get; set;}
public string CustomerName {get; set;}
public List<ExpenseLineItem> LineItems {get; set;}
}
public class ExpenseLineItem {
public DateTime ExpenseDate {get; set;}
public Decimal Amount {get; set;}
public string Description {get; set;}
}
過去,我通過重復 ExpenseLineItem 類中的信息來實現這一點。
public class ExpenseLineItem {
public string EmployeeName {get; set;}
public string CustomerName {get; set;}
public DateTime ExpenseDate {get; set;}
public Decimal Amount {get; set;}
public string Description {get; set;}
}
我將使用以下 LINQ 語句,其中importedData
是ImportedExpense
類型的集合
var expenseCollection = importedData.GroupBy(x =>
new
{
x.EmployeeName,
x.CustomerName
})
.Select (y => new Expense()
{
EmployeeName = y.Key.EmployeeName,
CustomerName = y.Key.CustomerName,
LineItems = y.ToList();
});
但是,我想完成同樣的事情,而不必重復 Expense 和 ExpenseItem 類中的信息。
我將如何形成 LINQ 查詢來完成此操作? 如果可能的話,使用流暢的語法,因為我對它與查詢語法更熟悉。
我不確定我是否正確理解了您的問題,但是如果您想將ImportedExpense
轉換為Expense->ExpenseLineItem
的層次結構,那么您的代碼就差不多了。 嘗試這個:
var expenseCollection = importedData.GroupBy(x =>
new
{
x.EmployeeName,
x.CustomerName
})
.Select (y => new Expense()
{
EmployeeName = y.Key.EmployeeName,
CustomerName = y.Key.CustomerName,
LineItems = y.Select(ie => new ExpenseLineItem()
{
ExpenseDate = ie.ExpenseDate,
Amount = ie.Amount,
Description = ie.Description
}).ToList();
});
有一個GroupBy
擴展,可讓您對分組項目進行投影。 您可以使用它來投影按匿名類型分組的ExpenseLineItem
和其中的其他數據點。
在代碼中它看起來像這樣:
var expenseCollection = importedData
.GroupBy
(
x => new { x.EmployeeName, x.CustomerName },
x => new ExpenseLineItem
{
ExpenseDate = x.ExpenseDate,
Amount = x.Amount,
Description = x.Description
}
)
.Select
(
y => new Expense
{
EmployeeName = y.Key.EmployeeName,
CustomerName = y.Key.CustomerName,
LineItems = y.ToList()
}
);
或者,您可以在選擇中進行投影:
var expenseCollection = importedData
.GroupBy(x => new { x.EmployeeName, x.CustomerName })
.Select
(
y => new Expense
{
EmployeeName = y.Key.EmployeeName,
CustomerName = y.Key.CustomerName,
LineItems = y.Select
(
item => new ExpenseLineItem
{
ExpenseDate = item.ExpenseDate,
Amount = item.Amount,
Description = item.Description
}
).ToList()
}
);
您可以將投影移出到單獨的方法或強制轉換運算符,但我認為上面的內容非常透明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.