3

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

2 Answers 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(); 

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

I actually tried the first one before I posted here, I just realized that my error is the same as yours, the freaking semi colon after return lol :)
actually the first one i saw has no semicolon on the return (or it just been delayed because you were too fast), anyway thanks man;)
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.