The following code loops through resultSet
and populates list a of SomeType
.
The resultSet
itself is an anonymous type with two properties
var resultSet = SomeCollection.Select(x => new {
FirstProp = x,
SomeMembers = SomeLinkCollection.Where(l => l.SomeId == x.SomeId)
.Select(l => AnotherCollection[l.Id])
});
var result = new List<SomeType>();
foreach (var currentGroup in resultSet) {
result.Add(new SomeType {
Prop1 = currentGroup.Item.Id,
Prop2 = currentGroup.Item.Name,
Prop3 = currentGroup.SomeMembers.OrderBy(x => x.Name)
});
}
To remove setting up new Sometype
instances I created a mapper class/interface using dynamic type to split the responsibility and use dependency injecton:
public class SomeMapper : ISomeMapper {
public List<SomeType> Map(dynamic resultSet) {
return resultSet.Select(new SomeType {
Prop1 = currentGroup.Item.Id,
Prop2 = currentGroup.Item.Name,
Prop3 = ((IEnumerable<AnotherType>)resultSet.SomeMembers)
.OrderBy(x => x.Name)
});
}
}
So the code above becomes:
return resultSet.Select(SomeMapper.Map);
Error
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)
I tried few tricks with explicit cast to SomeType
but it fails at run-time
return (List<SomeType>)groupSet.Select(statusGroupMapper.Map);
Unable to cast object of type
'WhereSelectListIterator2[AnotherType,System.Collections.Generic.List
1[SomeType]]' to type 'System.Collections.Generic.List`1[SomeType]'.