我需要重构此代码,以便数据服务不会在每个行项目中查询两个workType。提前谢谢。
_attributeGroups = attributeGroups.Select(attributeGroupRowModel =>
new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = workTypes.First(wt => wt.Id == attributeGroupRowModel.WorkTypeId).Description,
IsExpired = workTypes.First(wt => wt.Id == attributeGroupRowModel.WorkTypeId).IsExpired, //todo: not efficient, to be refactored
}).ToList();
答案 0 :(得分:6)
_attributeGroups = attributeGroups.Select(attributeGroupRowModel =>
{
var wt = workTypes.First(x => x.Id == attributeGroupRowModel.WorkTypeId);
return new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = wt.Description,
IsExpired = wt.IsExpired,
};
}).ToList();
或者如果您更喜欢LINQ:
_attributeGroups =
(from attributeGroupRowModel in attributeGroups
let wt = workTypes.First(x => x.Id == attributeGroupRowModel.WorkTypeId)
select new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = wt.Description,
IsExpired = wt.IsExpired,
}).ToList();
答案 1 :(得分:4)
您可以使用statement lambda代替表达式lambda。语句lambda允许您(其中包括)定义变量:
_attributeGroups = attributeGroups.Select(attributeGroupRowModel =>
{
var w = workTypes.First(wt => wt.Id == attributeGroupRowModel.WorkTypeId);
return new AttributeGroupRowModel()
{
Name = attributeGroupRowModel.Name,
WorkType = w.Description,
IsExpired = w.IsExpired,
};
}).ToList();