简体   繁体   中英

looking for a better way to get a count-per-city

Im trying to get a count on how many people live in a certain city. I have a database with people in it, and that table has a foreign key linking a certain person to a city, which is another table.

example:

City z: 5 people

City y: 10 people

City x: 4 people

im able to get these results back, but i just dont like the way i'm doing it, as i am calling the database x amount of times.

 public List<int> getStuff(List<int> listOfCityIDs )
    {
       var returnList = new List<int>();
       foreach (int z in listOfCityIDs)
        {
             returnList.Add((from x in conn.people
                             where x.city == z
                             select x).Count());
        }
        return returnList;
    }

im pretty sure there's a better/more efficient way of doing it with some LINQ, but i can't seem to find how.

any ideas?

kind regards, Jane

This will translate into SQL statements nicely.

conn.people.GroupBy(p => p.city).Select(p => new { City = p.Key, Count = p.Count()});

This will get them all. If you want based for certain cities, try

conn.people.Where(p => listOfCityIDs.Any(c => c == p.city))
  .GroupBy(p => p.city).Select(p => new { City = p.Key, Count = p.Count()});

In case you want a cleaner syntax and it works as deferred query

var g = from c in cities
    join p in people
    on c equals p.CityId
    group p.CityId by p.CityId into grouped
    select new { CityId = grouped.Key, Count = grouped.Count() };

Linq will optimize this for you when you are calling .Count() It realizes you don't want the whole result set.

Also remember if you are hitting a database (which I assume you are) the result set is an IQueryable which doesn't get executed until you try and get a value from it.

如何按城市ID对人进行分组?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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