Ritwik Bhar
Ritwik Bhar

Reputation: 284

C# mongodb driver throwing System.InvalidOperationException on linq query with OrderByDescending

I am using the following linq query to in c# to get a list of phone numbers from the Bill Collection sorted descending in according to the date&time of the creation of the bill. But this code gives me a System.InvalidOperationException. It works fine when i remove the Orderby clause. Any help?

 var result  = collection
                .AsQueryable<Bill>()
                .Where(bill => bill.customer_details.phone != null)
                .OrderByDescending(bill => bill.date_time)          
                .Select(_ => _.customer_details.phone)
                .Distinct()
                .ToList<string>();

Upvotes: 1

Views: 405

Answers (2)

procma
procma

Reputation: 1450

Isn't each item of collection unique? Do you really need Distinct? Although I do not have your data collection, I think Distinct is messing up the order. Try to omit Distinct or OrderByDescending

Upvotes: 2

Ritwik Bhar
Ritwik Bhar

Reputation: 284

Thank you @stuartd for suggesting me to use group by.

The following code worked for me

var result = collection
            .AsQueryable<Bill>()
            .Where(bill => bill.customer_details.phone != null)
            .OrderByDescending(bill => bill.date_time)
            .GroupBy(bill => bill.customer_details.phone)
            .Select(bill => bill.First().customer_details.phone)
            .ToList<string>();

Upvotes: 0

Related Questions