Can GroupBy and concat not be used together?

Viewed 52

I am trying to do some sorting based on the count() within a bundle, but I am not having much luck.

I have this sorting that works fine by sorting all the null values last

customerBasket.ItemsInBasket = customerBasket.ItemsInBasket.Where(s => s.BundleId != null)
                                                                       .OrderBy(s => s.BundleId)
                                                                       .ThenBy(s => s.ThisItemsCountWithinBundle)
                                                                       .Concat(customerBasket.ItemsInBasket.Where(s => s.BundleId == null))
                                                                       .ToList();

But then when I want to use concat again to sort "non full" bundles and put them last this cannot be done, I am trying this

 customerBasket.ItemsInBasket = customerBasket.ItemsInBasket.GroupBy(s => s.BundleId)
                                                                       .Where(s => s.Count() == 3)
                                                                       .Concat(customerBasket.ItemsInBasket.GroupBy(s => s.BundleId)
                                                                       .Where(s => s.Count() < 3)
                                                                       .SelectMany(s => s.ToList()));

But this gives me the following error message

Severity Code Description Project File Line Suppression State Error CS1929 'IEnumerable<IGrouping<string, ItemInBasket>>' does not contain a definition for 'Concat' and the best extension method overload 'Queryable.Concat(IQueryable, IEnumerable)' requires a receiver of type 'IQueryable' slapi C:\Users\Matt\source\repos\SLAPI\Utils\BasketHelpers.cs 20 Active

Not sure how I can fix this problem.

1 Answers

It looks like you have a misplaced parentheses causing you problems. Let's split the problematic one up to an equivalent version with a few temporary variables:

var full = customerBasket.ItemsInBasket.GroupBy(s => s.BundleId)
                                       .Where(s => s.Count() == 3);
var nonFull = customerBasket.ItemsInBasket.GroupBy(s => s.BundleId)
                                          .Where(s => s.Count() < 3)
                                          .SelectMany(s => s.ToList());
customerBasket.ItemsInBasket = full.Concat(nonFull);

This is what you typed, and is giving the error. Hopefully, this shows where the problem is coming from (SelectMany is changing the type of nonFull, so it is not something you can Concat with full). You need to move the SelectMany from nonFull to after the Concat.

In the version without the temporaries, this should be as simple as moving a closing parentheses.

Related