0

I’m writing a LightSwitch application and i could do with some advice.

I wanted to calculate the total number of child objects related to the parent object that fulfil the criteria of being true and related to the Client.

partial void OpenPositions_Compute(ref int result)
{
    foreach (Position position in this.DataWorkspace.ApplicationData.Positions)
    {
        if (position.IsPositionOpen && position.Client.Id == this.Id)
        {
            result++;
        }
    }
}

I did experiment with calculating the number of Positions a client had without using a foreach loop and i came up with this:

partial void TotalPositons_Compute(ref int result)
{
    result += this.Position.Count();
} 

Question 1: Is it possible to write snippet 1 in a better/more efficient way? Perhaps as a lambda equation? (or similar to the second code snippet)

Question2: What benefits would a lambda equation give other than readability of code?

Chomp
  • 114
  • 2
  • 13
  • It seems to me this is the most readable option, forcing it into a lambda would only reduce the lines of code. – MrFox Apr 16 '12 at 22:07

1 Answers1

2

Question 1:

partial void OpenPositions_Compute(ref int result)
{
    result = this.DataWorkspace.ApplicationData.Positions
        .Count(p => p.IsPositionOpen && position.Client.Id == this.Id);
}

Question 2:

It depends on usage. In this case, the biggest advantage is concise code, since you can use LINQ without having to re-implement the counting functionality. Performance can sometimes be increased. Using LINQ as an example again, LINQ uses deferred execution to prevent executing code until it is needed.

Usually, the lambda is not the solution, rather, it is part of the solution. Using LINQ is generally the solution for thing like this.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148