Conditionally Selecting Sums RRS feed

  • Question




    In my current system, we dynamically generate a SQL string based on criteria chosen by the user.  Some queries allow the user to include additional fields in the result set and some of these additional fields are sums.  Currently, if the user doesn't want these additional sum fields, then we don't add in the SQL for them (so that the additional aggregation doesn't happen and so that the extra data isn't brought over).


    I was hoping that if I had a bool, includeSum, that I could do something like:

    from person in context.Person

    select new


    Sum = includeSum ? Sum(person.Age) : 0


    where linq to sql would know not to include the sum at all in the sql if the local bool is false.  However, this doesn't seem to work.  Is it possible to have conditional selection in linq to sql?



    Tuesday, November 4, 2008 8:50 PM

All replies

  • Hi  lotrij

    These are the some of the examples of summing inside linq.

    Yes you can have conditional selection also...

    var query1  = from o in orders
                                where o.CustomerID == c.CustomerID
                                select o.OrderDetails.Sum(od => _
                                    od.UnitPrice * od.Quantity)).Sum()


    var query2 = from income in data.Incomes
                 group income by into result
                 select new
                     Name = result.Key,
                     Sum = result.Sum(i => i.income)

    I hope this one will help you people out.



    Friday, November 7, 2008 7:32 AM