The linq query markup that uses OrderBy

I want to return a list of a specific entity, grouped by a specific property, sorted in descending order by time stamp, and paginated (using Skip and Accept). I got it:

container.CoinMessageSet.Where( c => c.MessageState != MessageStateType.Closed && (c.DonorOperator.OperatorCode.Equals("opcode") || c.RecipientOperator.OperatorCode.Equals("opcode")) ).OrderByDescending(c => c.TimeStamp) .GroupBy(c => c.Reference).Skip(x).Take(100); 

After execution, I got an exception:

 The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'. 

... I called OrderBy () (albeit Descending), and I called it before Skip ()! What am I missing?

+7
source share
2 answers

You did not order groups; you need to do this before you can make the page. For example:

 .GroupBy(c => c.Reference).OrderBy(grp => grp.Key).Skip(x).Take(100); 

(you can also replace OrderByDescending if you want the groups to be in reverse order)

Also: as you group, the order in the source data is pretty much pointless; you could remove OrderByDescending(c => c.TimeStamp) .

So the net result is:

 var query = container.CoinMessageSet.Where( c => c.MessageState != MessageStateType.Closed && (c.DonorOperator.OperatorCode.Equals("opcode") || c.RecipientOperator.OperatorCode.Equals("opcode")) ).GroupBy(c => c.Reference).OrderBy(grp => grp.Key) .Skip(x).Take(100); 

or perhaps:

 var query = (from c in container.CoinMessageSet where c.MessageState != MessageStateType.Closed && (c.DonorOperator.OperatorCode == "opcode" || c.RecipientOperator.OperatorCode == "opcode") group c by c.Reference into grp orderby grp.Key select grp).Skip(x).Take(100); 
+7
source

This is most likely due to GroupBy after OrderByDescending .

I think you can try:

 container.CoinMessageSet.Where( c => c.MessageState != MessageStateType.Closed && (c.DonorOperator.OperatorCode.Equals("opcode") || c.RecipientOperator.OperatorCode.Equals("opcode")) ).OrderByDescending(c => c.TimeStamp) .GroupBy(c => c.Reference).OrderByDescending(c = > c.Key).Skip(x).Take(100); 
+2
source

All Articles