C# 重构这个Lambda表达式

C# 重构这个Lambda表达式,c#,lambda,C#,Lambda,我需要重构这段代码,以便数据服务不会对每行项查询两个工作类型。提前谢谢 _attributeGroups = attributeGroups.Select(attributeGroupRowModel => new AttributeGroupRowModel() { Name = attributeGroupRowModel.Name, 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();
可以使用表达式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();
或者,如果您更喜欢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();

事实上,在我发布到这里之前,我试过了第一个,我刚刚意识到我的错误和你的一样,返回后的分号很奇怪lol:)事实上,我看到的第一个返回上没有分号(或者只是因为你太快而延迟了),无论如何,谢谢你;)
_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();