ilija veselica
ilija veselica

Reputation: 9574

Sum properties using LINQ

DealsThisMonthOpen = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open").Count(),
DealsThisMonthLost = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost").Count(),
DealsThisMonthWon = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won").Count(),
DealsThisMonth = DealsThisMonthOpen + DealsThisMonthLost + DealsThisMonthWon;

The last line is not syntax correct. Is it possible to do it like this or I will have to write query for this Property to calculate sum?

Thanks

Upvotes: 1

Views: 645

Answers (3)

abatishchev
abatishchev

Reputation: 100366

btw, Count() also supports predicate argument: http://msdn.microsoft.com/en-us/library/bb535181.aspx

So you can:

var a = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open"),
var b = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost"),
var c = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won"),

new foobar
{
    DealsThisMonthOpen = a,
    DealsThisMonthLost = b,
    DealsThisMonthWon = c,
    DealsThisMonth = a + b + c
};

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245509

Maybe I'm missing something, but that should definitely work.

The Count() method returns an int so DealsThisMonthOpen, DealsThisMonthLost, and DealsThisMonthWon are all integer values. DealsThisMonth is just the sum of those three integer values.

You could also make it a little cleaner (unless you need the three distinct values for something else later:

var dealsThisMonth = deals
    .Count(d => d.DateCreated.Month == date.Month
        && (new string[] { "Open", "Lost", "Won" }).Contains(d.DealStatus));

Upvotes: 2

Lucas B
Lucas B

Reputation: 12013

Have you considered an extension method? Where you provide the sum feature.

Upvotes: 0

Related Questions