Code Reduction in C# 3

C# 3.0 is god like. Undeniably. The ability to reduce your code is amazing. Now, I understand the code zealots out there will say "Yeah, but X language has been able to do this for years". Well I don't really care about X language truth be told. The .NET platform is so widely deployed and supported now I don't really see why in 9/10 cases I should use language X.

Consider the following basic example, of calculating an Inverse Distance Weighted plot of signal strength of a given location given a set (plots) of locations and their corresponding signal measure.

The formula is simple, for a given point x, the strength is the sum of wk(x) (one over the distance between the two points to the power of a fixed parameter p) times uk (the value at k) over the sum of wk(x):

 

Traditionally, this would yeild the following code:

double sumWkUk = 0;
double sumWk = 0; 
 
foreach(Location loc in plots)
{
sumWkUk += wk(x, loc) * loc.Value;
sumWk += wk(x, loc);
}
 
x.Value = sumWkUk / sumWk;

 

Not too much code, but this can be reduced a lot. Consider using the C# 3.0 sum operator:

 

x.Value = plots.Sum(xk => wk(x, xk) * xk.Value)
/ plots.Sum(xk => wk(x, xk));

 

Wait, what, did we just reduce that to ONE LINE of code? Shit.

Are you listening Java? No, thought not, no wonder you are still losing the great programming race (or maybe I am just bitter).

Summary:

- Less code to maintain is good.

- Gives us less chances for errors

- makes it easier to read and understand (in this case at least)

 

Opinions? Discuss? Don't care? Don't even know what you are doing here?

Post Metainfo

Code Reduction in C# 3 was published on Friday, May 2nd, 2008 at 6:21 pm and is filed under Keima, Programming, Work. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

« Microsoft gave me free Ice Cream | Real Simple Test Driven Development in Visual Studio »

2 people commented on “Code Reduction in C# 3”

extipHithhjz

January 26th, 2010

kim kardashian ray j sex tape kim kardashian sex tape watch kim kardashian sex tape
http://digg.com/celebrity/Kim_Kardashian_Sues_Over_Sex_Tape – kim kardashian sex tape


TanaLetrib

April 29th, 2010

Dating van orin. Cerita sex dating. Dating branch.
White woman dating. Dating elmendorf. Dating daviston.
Dating deer grove. Dating summerland. Carolina dating gay in north sex.


Leave a reply