lincx
lincx

Reputation: 409

Refactor this Lambda Expression

I need to refactor this code so that the data service wont query two workTypes per row item. Thanks in advance.

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

Upvotes: 3

Views: 144

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

or if you prefer 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();

Upvotes: 6

Heinzi
Heinzi

Reputation: 172220

You can use a statement lambda instead of an expression lambda. A statement lambda allows you, among other things, to define variables:

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

Upvotes: 4

Related Questions