0

Example table:

Name          Work        City

Bob           Work1       City2
Frank         Work2       City1
Will          Work3       City1
Lisa          Work4       City3
Alex          Work5       City2

How do I with entity framework find out how many names lives in a city?

So the output I get is "2,2,1" (2 City2, 2 city1, 1 city3)

user10384441
  • 123
  • 1
  • 7
  • 1
    Post the code you tried, table names, database names... – anmarti Sep 19 '18 at 12:40
  • I'd do this in two stages. First, get a list of unique city names. Second, count how many rows have that city name. – Robin Bennett Sep 19 '18 at 12:42
  • 3
    Possible duplicate of [SQL to Entity Framework Count Group-By](https://stackoverflow.com/questions/11564311/sql-to-entity-framework-count-group-by) – PaulF Sep 19 '18 at 12:47
  • `context.TableName.GroupBy(x => x.City).Select(x => new { name = x.Key, count = x.Count() });` – CodingYoshi Sep 19 '18 at 12:48
  • @RobinBennett I was thinking that that is what i need to do but i can't figure out how. Could you please explain how to me? – user10384441 Sep 19 '18 at 12:58

2 Answers2

0

If all are in the same table then the comment given by @CodingYoshi is the correct.

But if All are different table then its required for us to understand the Table structure.

You can do it multiple ways.

  1. Join and Group by the table based on conditions.
  2. Get each record and count up using for loop (not recommended)
Mohsin Tolat
  • 125
  • 2
  • 15
0

assuming that the data is as noted in your question you can do as follows

set.GroupBy(x => x.City)
   .Select(x => new { NamesCount = x.Distinct().Count(), City = x.Key })

if you are using linq-to-sql, you'll need to add a ToList before Select like this

set.GroupBy(x => x.City)
   .ToList()
   .Select(x => new { NamesCount = x.Distinct().Count(), City = x.Key })
Ahmed Sherien
  • 313
  • 1
  • 2
  • 15