简体   繁体   English

LINQ IQueryable具有分组和计数

[英]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: 在我的.net Core 2.0 Razor Pages项目中,我声明了一个这样的列表,其中MyData是链接到Entity Framework数据集的模型:

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: 然后,在我的OnGet()方法中,我知道可以查询此内容以生成一个可以循环通过的列表,如下所示:

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? 如果我想返回一个按用户名分组并包含该用户名所有出现次数的列表,那么我的LINQ查询会是什么样?

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. 我是Core 2.0和Linq的新手,所以任何帮助都将非常有用。

You are declaring MyDataIQ as a IQueryable<MyData> , but you are creating IQueryable of anonymous type. 您将MyDataIQ声明为IQueryable<MyData> ,但是您正在创建匿名类型的IQueryable。

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. 编辑:Ups,我看到Mike Hixson已经在评论中回答了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM