Molenpad
Molenpad

Reputation: 1044

LINQ IQueryable with group by and count

In my .net Core 2.0 Razor Pages project, I am declaring a List like this, where MyData is a model linked to an Entity Framework dataset:

public IList<MyData> MyData { get; set; }

For simplicity, let's say my data looks like this:

ID | UserName | LogOn
1  | User1    | 25/03/2018 12:54
2  | User2    | 25/03/2018 09:43
3  | User1    | 24/03/2018 18:23
4  | User3    | 24/03/2018 08:16
5  | User2    | 23/03/2018 17:12

..etc

Then in my OnGet() method I know I can query this to produce a list I can loop through, like so:

IQueryable<MyData> MyDataIQ = from i in _context.MyData select i;

MyData = await MyDataIQ.ToListAsync();

If I wanted to return a list which is grouped by UserName with a count of all occurrences of that UserName, what would my LINQ query look like?

I've tried this:

IQueryable<MyData> MyDataIQ = from i in _context.MyData group i by i.UserName into grp select new {key = grp.Key, cnt = grp.Count()};

But this just gives me a type conversion error.

I have the raw data, I just want to show it on the view grouped in this fashion.

I'm new to Core 2.0 and also Linq, so any help will be massively useful.

Upvotes: 2

Views: 3797

Answers (1)

user3188639
user3188639

Reputation:

You are declaring MyDataIQ as a IQueryable<MyData>, but you are creating IQueryable of anonymous type.

This should work:

var MyDataIQ = from i in ctx.MyData group i by i.UserName into grp select new { key = grp.Key, cnt = grp.Count() };

foreach (var a in MyDataIQ)
{
    Console.WriteLine($"{a.key} {a.cnt}");
}

The result:

User1 2
User2 2
User3 1

EDIT: Ups, I see that Mike Hixson already answered in the comment.

Upvotes: 3

Related Questions