带计数的C#查询

Loï*_*aye 0 c# linq

我有一个拥有多个属性的用户列表,我想知道谁和如何拥有相同的代码(这是一个用户属性)

例如 :

  • 用户1:雅各布,代码1
  • 用户2:查理,代码1
  • 用户3:托马斯,代码2

我需要查询并得到如下结果:

+--------+--------+
| Object |  Count |
+--------+--------+
| user 1 |    2   |
| user 2 |    2   |
| user 3 |    1   |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

"2",因为2个用户具有相同的代码和"1",因为只有一个拥有代码

请有人帮帮我吗?

小智 9

你可以使用这个linq.改变,tablenamefield name根据你的.

(from user in _context.Users
             let count = _context.Users.Where(p=>p.code == user.code).Count()
                 select new {user.username, count = count}).ToList()
Run Code Online (Sandbox Code Playgroud)