Andreas Furster
Andreas Furster

Reputation: 1638

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"

Upvotes: 2

Views: 3599

Answers (3)

tolanj
tolanj

Reputation: 3724

Just use:

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

Upvotes: 3

EriF89
EriF89

Reputation: 732

An alternative way of achieving this is:

var sortedNames = context
    .Items
    .Where(b => !b.Deleted)
    .Select(b => b.Name)
    .OrderBy(b => b.Name)
    .ToArray();

result = Enumerable.Range(1, sortedNames.Length)
    .ToDictionary(i => i, i => sortedNames[i - 1]);

To get zero-based numbering, use Enumerable.Range(0, sortedNames.Length) and sortedNames[i] instead.

Upvotes: 0

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

I think what you need is to have the item name as the key instead the count as the key, because if there is two items that have the same count, it will throw exception that the key has been added.

Then you can Use GroupBy before ToDictionary so that you can count it.

result = context
    .Items
    .Where(b => !b.Deleted)
    .GroupBy(x => x.Name)
    .ToDictionary(g => g.Key, g => g.Count())
    .OrderBy(g => g.Key);

based on your updated comment, then what you need is

result = context
    .Items
    .Where(b => !b.Deleted)
    .OrderBy(b => b.Name)
    .AsEnumerable()
    .Select((v,i) => new { i, v.Name })
    .ToDictionary(g => g.i + 1, g => g.Name);

Note that you need to add AsEnumerable so that the Select clause works as linq to object (Select that accept index is not supported in L2S).

Upvotes: 7

Related Questions