Loïc Haye
Loïc Haye

Reputation: 71

C# query with count

I have a list of users having several properties and I want to know who and how had the same code (which is an user property)

For example :

I need to query and have a result like this :

+--------+--------+
| Object |  Count |
+--------+--------+
| user 1 |    2   |
| user 2 |    2   |
| user 3 |    1   |
+--------+--------+

"2" because 2 users have the same code and "1" because just one had the code

Can someone help me for this please?

Upvotes: 0

Views: 103

Answers (2)

Hieu Le
Hieu Le

Reputation: 1122

Let's try below code. I think it can help you well:

var result = mycontext.users.GroupBy(p=>p.User).Select(p=>new { Object  = p.Key, Count = p.Count()});

Upvotes: 1

jignesh patel
jignesh patel

Reputation: 982

You can get using this linq. change tablename and field name according to yours.

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

Upvotes: 9

Related Questions