Linq

by paet the pagan-gerbil 25. March 2010 12:43

I’ve just found out how to combine .Sum() with a where clause, and all it took was a further step into the murky world of Linq.

I got my tip-off from a fellow BlogEngine.NET blog user Gary Kilminster - http://cunningplan.co.uk/post/Extension-Methods.aspx – although it doesn’t look like his blog has been updated for a while.

I had a list of custom objects, and wanted to get the sum of all their ‘Cost’ values as long as they had a specific property in common. The bit of Gary’s code that really made it click for me was:

        string londonNames = (from c in db.Customers
                              where c.City == "London"
                              select c.CompanyName).Sum();

In my case, it became:

        int result = (from o in objectList
                      where o.OptionGroupId == specificId
                      select o.Cost).Sum();

It’s just so simple and easy. Hooray!

Tags: , ,

.Net Nooks and Crannies

by paet the pagan-gerbil 12. December 2009 21:07

I really love Stack Overflow. It’s so cool to have a link to many, many great coding minds to help with the minutiae of my learning process, whether through asking a question myself or finding that someone else asked something similar months ago.

The last question I asked was about public properties that should be read-only (usually List<T> or somesuch thing), but allow the user to add an item still. The answer was to use a class called ‘ReadOnlyCollection<T>’. This is one of many, many classes that I’ve never heard of but would be incredibly useful if I had!

When I get to the end of the first run of Wargame Tools, I’ll definately be refactoring it (especially since I plan to port the logic to an ASP.NET MVC 2.0 application and see how those work) and will be sure to blog about this class and how I find using it.

Tags: ,

Programming

Powered by BlogEngine.NET 1.6.0.0
Theme by Pete Fullergreen, based on one by Mads Kristensen

Shop at Amazon.co.uk
Find us on Facebook!