griegs
griegs

Reputation: 22760

Convert IGrouping to IQueryable

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?

Upvotes: 6

Views: 6511

Answers (3)

gotnull
gotnull

Reputation: 27214

Change your query to:

dc.CelebrityLocations.OrderByDescending(x => x.DateTime).AsQueryable().GroupBy(x => x.Celebrity).Select(x => x.First());

Upvotes: 4

Krizz
Krizz

Reputation: 11552

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);

Upvotes: 7

SLaks
SLaks

Reputation: 887469

You can just call AsQueryable().

Upvotes: -2

Related Questions