7

Is it possible to retrieve the Top n records from the Azure Table Storage using C#? I'm using .NET Core.

It would be great if I can get some references as well.

Please note that all my entities are stored using the Log Tail Pattern https://learn.microsoft.com/en-us/azure/cosmos-db/table-storage-design-guide#log-tail-pattern

Thanks, Praveen

1
  • Please include the code for how you (would) do it without the Top N condition. If you use Linq, see if adding .Take(n) works.
    – Peter B
    Commented Jun 4, 2018 at 14:26

2 Answers 2

13

You can use Take() method when creating your TableQuery:

TableQuery<T> query = new TableQuery<T>().Take(takeCount);

Or set the property TakeCount to specify it:

TableQuery<T> query = new TableQuery<T>();
query.TakeCount = takeCount;
4
  • Setting only the TakeCount didn't work for me. I had to follow this example and check the count of entities retrieved. Anyway, this answer was the first step to a working solution :) Commented Jan 24, 2020 at 9:18
  • Hi @Simonca. were you able to retrieve top entity? Thankful for a solution.
    – DCodes
    Commented Oct 16, 2020 at 12:30
  • Hi @DCodes! I've added an answer to this question with the solution we used, hope it helps. Commented Oct 17, 2020 at 12:53
  • Thank you so much for writing a concise and direct answer, with examples! Commented Nov 14, 2021 at 3:32
3

What we did to get top entities of a table is as follows:

var query = new TableQuery<TEntity>()
            .Where(partitionFilter)
            .Take(limit);

return await ExecuteQuery(table, query);

Created the query and used .Take(limit) to specify how many entities we wanted.

 do
 {
      var seg = await table.ExecuteQuerySegmentedAsync<TEntity>(query, token);

      token = seg.ContinuationToken;

      items.AddRange(seg);
 } while (token != null && items.Count < query.TakeCount);

In ExecuteQuery method we counted how many records were retrieved from the table. This is how we did it and worked, I assume that in order to take top n entities the limit should be set to n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.