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();
asked Sep 25, 2012 at 5:12

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();
answered Sep 25, 2012 at 5:16
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();
answered Sep 25, 2012 at 5:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.