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
lincx
4092 gold badges6 silver badges15 bronze badges
2 Answers 2
_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
Darin Dimitrov
1.0m277 gold badges3.3k silver badges3k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
lincx
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 :)
lincx
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;)
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
Heinzi
173k61 gold badges386 silver badges555 bronze badges
Comments
lang-cs