How to convert C# Linq to cosmos query

Juhi Saxena 41 Reputation points
2022-10-10T12:58:23.73+00:00

Hi Everyone!

We have below C# LINQ query to group from a cosmos IQueryable container and then order by some attributes.

var unitPrices = unitPriceContainer.ToList()
.GroupBy(u => new { u.SupplierId, u.Sku, u.SupplierPackSize })
.Select(s => s.OrderByDescending(o => o.CreatedDate).ThenByDescending(t => t.EffectiveFrom).First())
.ToList();

We want to convert this to Cosmos query so that it can be accessible using FeedIterator.

Is there any workaround to have same query converted or just group by. So that, order by can further be queried over the output of group by. Please suggest.

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,543 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Sina Salam 7,441 Reputation points
    2022-10-10T16:44:08.76+00:00

    Hi @Juhi Saxena

    The Azure Cosmos DB query provider performs a best effort mapping from a LINQ query into a Cosmos DB SQL query. If you want to get the SQL query that is translated from LINQ, use the ToString() method on the generated IQueryableobject.

    There is a guide on how convert LINQ to SQL translation in the below Microsoft link.

    https://learn.microsoft.com/en-us/azure/cosmos-db/sql/sql-query-linq-to-sql

    Hope this will be helpful and serve as a library for you.

    Hope to read from you.

    Cheers.
    Sina

    0 comments No comments