Created
December 15, 2011 15:59
-
-
Save robertgreiner/1481618 to your computer and use it in GitHub Desktop.
Use LINQ to perform calculations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace LINQSum | |
{ | |
public class SumNumbers | |
{ | |
private int[] numberList = {1, 2, 4, 8, 16, 32}; | |
public int SumUsingLinq() | |
{ | |
return numberList.Sum(num => num); | |
} | |
public int SumUsingForeach() | |
{ | |
var sum = 0; | |
foreach (int num in numberList) | |
{ | |
sum += num; | |
} | |
return sum; | |
} | |
public double SumSquaresUsingLinq() | |
{ | |
return numberList.Sum(num => Math.Pow(num, 2)); | |
} | |
static void Main(string[] args) | |
{ | |
var sum = new SumNumbers(); | |
var linqSum = sum.SumUsingLinq(); | |
var foreachSum = sum.SumUsingForeach(); | |
var sumSquares = sum.SumSquaresUsingLinq(); | |
Console.WriteLine("LINQ Sum: {0}", linqSum); | |
Console.WriteLine("ForeachSum: {0} ", foreachSum); | |
Console.WriteLine("SumSquares: {0} ", sumSquares); | |
Console.ReadKey(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using NUnit.Framework; | |
namespace LINQSum.Tests | |
{ | |
[TestFixture] | |
public class SumNumbersTests | |
{ | |
[Test] | |
public void ShouldAddAllValuesUsingForeach() | |
{ | |
var sum = new SumNumbers(); | |
Assert.AreEqual(63, sum.SumUsingForeach()); | |
} | |
[Test] | |
public void ShouldAddAllValuesUsingLinqExpression() | |
{ | |
var sum = new SumNumbers(); | |
Assert.AreEqual(63, sum.SumUsingLinq()); | |
} | |
[Test] | |
public void LinqExpressionAndForeachSumShouldBeEqual() | |
{ | |
var sum = new SumNumbers(); | |
Assert.AreEqual(sum.SumUsingForeach(), sum.SumUsingLinq()); | |
} | |
[Test] | |
public void ShouldSumTheSquaresOfAllValuesUsingLinqExpression() | |
{ | |
var sum = new SumNumbers(); | |
Assert.AreEqual(1365.0, sum.SumSquaresUsingLinq()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment