Major Productions
Major Productions

Reputation: 6042

Need help figuring out a LINQ query w/ EF

I have a bunch of entities I'd like to list in a wiki-like manner, where they would be organized by the first letter of their title, followed by a count of how many entities exist per letter. So, something like:

A (5)
B (7)
C (4)
etc.

I'm not sure how to go about it, though. A rough pseudocode version:

from g in Games select g.title, /* count */
    where /* g.title.firstLetter */ ASC

The commented out parts are where I'm stuck. Any ideas?

Upvotes: 0

Views: 49

Answers (3)

Akhil
Akhil

Reputation: 7600

var query = from g in Games
            group g by g.title[0] into cg
            select new { FirstLetter = cg.Key, Count = cg.Count() };

Upvotes: 1

David
David

Reputation: 3804

context.Games
       .GroupBy(g => g.title.FirstOrDefault())
       .Select(g => new {g.Key, Count = g.Count()})

Upvotes: 1

Darren Kopp
Darren Kopp

Reputation: 77627

from game in games
group game by game.Title.Substring(0,1) into g
select new {
    Key = g.Key,
    Count = g.Count()
};

Free handed that, so there may be compiler errors, but I believe that should be the linq query to get you what you want.

Upvotes: 5

Related Questions