I have a basic LINQ Query that looks like the following:
var results = from x in context.MyEntities
where (x.CustomerName != null)
select new Customer()
{
CustomerID = x.CustomerID,
FirstName = x.FirstName,
LastName = x.LastName,
Gender = x.Gender,
BirthMonth = x.BirthMonth
};
results = results.GroupBy(x => x.Gender);
results = results.GroupBy(x => x.BirthMonth);
bool onlyShowKnownGenders = GetWhetherToShowOnlySetGenders();
if (onlyShowKnownGenders) {
results = results.Where(x => ((x.Gender == 1) || (x.Gender == 2)));
}
If I comment out the two “GroupBy” lines, my code works fine. However, I now have a need to group the results. When I include the two “GroupBy” lines, I receive an error that says:
Cannot implicitly convert type ‘System.Linq.IQueryable>’ to ‘System.Linq.IQueryable’. An explicit conversion exists (are you missing a cast?)
My question is, I’m not sure how to do the cast in this case. Can someone please help me out?
Thank you!
The problem is that after you call a group by you don’t get back an enumerable of (in this case) Customers. You get back an enumerable of groups.
A group of customers doesn’t have a BirthMonth property.
What exactly are you trying to do here?
Is this what you want?
This would give you a group of groups at the end.
(I also incorporated dasblinkenlight’s answer in that you can’t re-use the same variable since the types are different).