If I use Select on IQueryable on my entity framework result I'll get 4 items as a result.
If I use Select on an IQueryable.ToList() I get all 36 items.
Here's code of the function:
public ImagesGetModelView Get(int start, int count)
{
if (count <= 0) count = 9;
else if (count > ImageHandler.MaxResult) count = ImageHandler.MaxResult;
IQueryable<Image> imagesList = ImagesHandler.FetchRangeScore(start, count)
.Where(m => m.Domain == Database.Enums.ImageDomain.Gfycat);
//Works using list :(
//var list = imagesList.ToList();
//Select all subreddits once
//Returns 4 instead of 36 if not using the list ...
//Returns 1 instead of 2 with Distinct() if not using the list
IEnumerable<Subreddit> subreddits = imagesList
.Select(m => m.Subreddit); //.Distinct();
ImagesGetModelView result = new ImagesGetModelView()
{
Items = imagesList,
Subreddits = subreddits
};
return result;
}
public IQueryable<Image> FetchRangeScore(int a_start, int a_count)
{
return Repository.AllQueryable().OrderByDescending(m => m.Score)
.Skip(a_start).Take(a_count);
}
Out of the 36 items 2 Subreddits will be distinct. But since only 4 out of 36 are fetched from Select() it only finds 1 distinct.
So is there anything I can do with the LINQ expressions to get correct data so the distinct statement works or do I have to make it into a List before continuing with the Select & Distinct functions?
Edit:
by moving the where satement from the end to the start of the whole query.
It appears to work correctly now. Select returns all 36 items e.t.c... which in turn makes the Distinct work since it can find more than 1 unique value.
public IQueryable<Image> FetchRangeScore(int a_start, int a_count)
{
return Repository.AllQueryable()
.Where(m => m.Domain == Database.Enums.ImageDomain.Gfycat)
.OrderByDescending(m => m.Score)
.Skip(a_start).Take(a_count);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…