This project has moved and is read-only. For the latest updates, please go here.

Sum() question

Jun 12, 2014 at 12:56 PM

Is there a way I could do a Sum() but after selecting a subset of a collection?
For example:
r.Sum( item => item.CustomerId == "my_id", item.Price);
Thanks for your help!
Jun 12, 2014 at 1:10 PM
Edited Jun 12, 2014 at 1:11 PM
var total = r.Where(item => item.CustomerId == "my_id").Sum(item => item.Price)
Something along those lines...
Jun 12, 2014 at 1:36 PM
Thanks! Was keeping my fingers crossed, but unfortunately, I got this error:
System.NotSupportedException: The Sum query operator is not supported.
at MongoDB.Driver.Linq.SelectQuery.TranslateMethodCall (System.Linq.Expressions.MethodCallExpression) <IL 0x002c2, 0x0055f>
at MongoDB.Driver.Linq.SelectQuery.Translate (System.Linq.Expressions.Expression) <IL 0x0003f, 0x000eb>
at MongoDB.Driver.Linq.MongoQueryTranslator.Translate (MongoDB.Driver.Linq.MongoQueryProvider,System.Linq.Expressions.Expression) <IL 0x00027, 0x00083>
at MongoDB.Driver.Linq.MongoQueryProvider.Execute (System.Linq.Expressions.Expression) <IL 0x00010, 0x0001b>
at MongoDB.Driver.Linq.MongoQueryProvider.Execute<long> (System.Linq.Expressions.Expression) <IL 0x00032, 0x0004f>
at System.Linq.Queryable.Sum<Docker.Ent.ImageEntity> (System.Linq.IQueryable`1<Docker.Ent.ImageEntity>,System.Linq.Expressions.Expression`1<System.Func`2<Docker.Ent.ImageEntity, long>>) <0x0013a>

Simplifying the query by removing the Where() part doesn't help.
Is Sum() supposed to work, is it just me?

Here's the (very simple) code I use:
var imgRepo = new MongoRepository.MongoRepository<Ent.ImageEntity>(ConfigurationManager.AppSettings["Global.Db.Url"]);
return (ulong)imgRepo/*.Where (i => i.CustomerId == customerId)*/.Sum (i => i.Size);
I'm using MongoRepository 1.6.5 and mongocsharpdriver 1.9.1
Jun 12, 2014 at 1:51 PM
Edited Jun 12, 2014 at 1:51 PM
Yeah, sorry, my bad. Sum() is not (yet) supported by the underlying driver. See this ticket.

What you can do is add a .ToArray() or .ToList() before the .Sum() so that you can apply the Sum() to the result using Linq2Objects.
Jun 12, 2014 at 3:40 PM
Thanks. That's precisely what I wanted to avoid, since for me I'd have to retrieve a lot of objects before being able to do the Sum() operation.
Well, if there is no other option for now... Guess I have no choice ;)
Thanks again