c# - 使用 LINQ 将记录展平到父/子对象。无需重复数据
问题描述
我试图更好地理解使用 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 语句 where importedData
is a collection of typeImportedExpense
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();
});