1

I have a

IGrouping<string, MyObj> 

I want to transform it into another IGrouping. For argument sake the key is the same, but MyObj will transform into MyOtherObj i.e.

IGrouping<string, MyOtherObj>

I am using Linq2Sql but I can copy with this last bit not being transformable into SQL.

I want it to be still be an IGrouping<T,TT> because it is a recognised type and I want the signature and result to be apparent. I also want to be able to do this so I can break my link down a bit and put into better labelled methods. i.e.

GetGroupingWhereTheSearchTextAppearsMoreThanOnce()
RetrieveRelatedResultsAndMap()

Bundle up and return encased in an IEnumerable - no doubt as to what is going on.

I have come close by daisy chaining

IQueryable<IGrouping<string, MyObj>> grouping ....

IQueryable<IGrouping<string, IEnumerable<MyOtherObj>>> testgrouping = grouping.GroupBy(gb => gb.Key, contacts => contacts.Select(s => mapper.Map<MyObj, MyOtherObj>(s)));

but I end up with

IGrouping<string, IEnumerable<MyOtherObj>>

I know it is because of how I am accessing the enumerable that the IGrouping represents but I can't figure out how to do it.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jon H
  • 1,061
  • 4
  • 13
  • 32

1 Answers1

0

You could just flatten the groupings with SelectMany(x => x) then do the GroupBy again, but then you're obviously doing the work twice.

You should be able to do the projection as part of the first GroupBy call instead.

Alternatively, you can add your own implementation of IGrouping, as described here What is the implementing class for IGrouping?, then simply do:

groups.Select(g => new MyGrouping(g.Key, g.Select(myObj => Mapper.Map<MyObj,MyOtherObj>(myObj))))
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46