Search code examples
c#linqentity-frameworkdictionarycounter

C# LINQ get count to dictionary


I got a LINQ query with Entity Framework (EF) and getting a list of items. Now I want to create a dictionary with the incrementing index of the item and the item itself.

I have it like this:

result = context
    .Items
    .Where(b => !b.Deleted)
    .OrderBy(b => b.Name)
    .ToDictionary(COUNTHERE, b => b.Name)

So the dictionary have to look like this:

1: "item1"
2: "item2"
3: "item5"
4: "item10"
5: "item100"

Solution

  • Just use:

    int count = 0;
    var result = context
        .Items
        .Where(b => !b.Deleted)
        .OrderBy(b => b.Name)
        .ToDictionary(b => ++count, b => b.Name);