3

我需要重构此代码,以便数据服务不会查询每个行项的两个工作类型。提前致谢。

        _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();
4

2 回答 2

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();
于 2012-09-25T05:16:21.357 回答
4

您可以使用语句 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();
于 2012-09-25T05:16:14.353 回答