3

I'm making a stadistics module and I need to do a GroupBy Operation with a Count to take the total visitors by country. I'm using MongoRepository (Link to Library)

I have this code in C# working fine, but I don't like the solution:

var repositoryIpFrom = new MongoRepository<IpFrom>();
var countries = repositoryIpFrom.Where(s => s.id == id).Select(s => s.Country).Distinct();

            foreach (var country in countries)
            {
                statisticsCountryDto.Add(new StatisticsCountryDto()
                {
                    Country = country,
                    Count = repositoryIpFrom.Count(s => s.id == id && s.Country == country)
                });
            }

            return statisticsCountryDto;

And this one with Linq (but it's not working... the error says GroupBy is not supported)

 var tst = repositoryIpFrom.Where(s=>s.id == id).GroupBy(s => s.Country).Select(n => new
            {
                Country = n.Key,
                Count = n.Count()
            });

Can I have any options to make the GroupBy and not make a lot of queries?

Thanks!!

chemitaxis
  • 13,889
  • 17
  • 74
  • 125

1 Answers1

2

Since you are not filtering through the query, you can resolve the query by inserting a AsEnumerable operation and then perform the grouping operations on the local data after the MongoDb driver is no longer involved.

var tst = repositoryIpFrom
            .Where(s=>s.id == id)
            .AsEnumerable()
            .GroupBy(s => s.Country)
            .Select(n => new
            {
               Country = n.Key,
               Count = n.Count()
            });
Steve Mitcham
  • 5,268
  • 1
  • 28
  • 56