Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IGrouping to IQueryable

Tags:

c#

linq

I have a model called CelebrityLocation which has, amongst other properties, a Celebrity model.

So;

public partial class CelebrityLocation
  public Celebrity Celebrity {get; set;}

I want to get a list of all the CelebrityLocation objects but group that by Celebrity within the CelebrityLocation.

I get a return type of IGroupng but I need to convert that to an IQueryable<CelebrityLocation>.

The below is what I have been trying so far.

IQueryable<CelebrityLocation> returnSet = (IQueryable<CelebrityLocation>) dc.CelebrityLocations.OrderByDescending(x => x.DateTime).GroupBy(x => x.Celebrity);

Edit

Is AutoMapper a viable solution in this case?

like image 252
griegs Avatar asked Jan 30 '12 23:01

griegs


2 Answers

Do you want to just get flat IQueryable<CelebrityLocation> just that grouped elements are next to each other?

If so, this should help:

IQueryable<CelebrityLocation> returnSet = dc.CelebrityLocations.OrderByDescending(x => x.DateTime).GroupBy(x => x.Celebrity).SelectMany(x => x);
like image 122
Krizz Avatar answered Oct 23 '22 05:10

Krizz


Change your query to:

dc.CelebrityLocations.OrderByDescending(x => x.DateTime).AsQueryable().GroupBy(x => x.Celebrity).Select(x => x.First());
like image 22
fulvio Avatar answered Oct 23 '22 06:10

fulvio