tags:

views:

140

answers:

5

Here's the c# code that I have:

private double get806Fees (Loan loan)
{
    Loan.Fee.Items class806;
    foreach (Loan.Fee.Item currentFee in loan.Item.Fees)
    {
        if (currentFee.Classification == 806) class806.Add(currentFee);
    }

    // then down here I will return the sum of all items in class806
}

Can I do this using linq? If so, how? I have never used linq and i've read in several places that using linq instead of a foreach loop is faster... is this true?

+4  A: 
loan.Item.Fees.
    Where(x => x.Classification == 806).
    Sum(x => x.SomeValueProperty)

Whether it is faster or not is debatable. IMO, both complexities are the same, the non-LINQ version may be faster.

leppie
While this is true, I personally favor the LINQ version over the non-LINQ because I think it expresses its intent more clearly and in less code.
David
+1  A: 
private double get806Fees(Loan loan)
{
    return load.Item.Fees.
        Where(f => f.Classification == 806).
        Sum(f => f.ValueToCalculateSum);
}

I'm assuming here that ValueToCalculateSum is also a double. If it's not then you have to convert it before it is returned.

RaYell
+2  A: 
var q =
  from currentFee in loan.Item.Fees
  where currentFee.Classification == 806
  select currentFee;

var sum = q.Sum(currentFee => currentFee.Fee);
Bob
+4  A: 

Similar to some existing answers, but doing the projection in the query, to make the Sum call a lot simpler:

var sum = (from fee in loan.Items.Fees
           where fee.Classification == 806
           select fee.SomeValueToSum).Sum();
Marc Gravell
A: 

All of the answers so far are assuming that you're summing up loan.Fees. But the code you actually posted calls Items.Add() to add each Item in loan.Fees.Items to an Items object, and it's that Items object (and not loan.Fees, which is also an Items object) that you say you want to sum up.

Now, if Items is just a simple collection class, then there's no need to do anything other than what people are suggesting here. But if there's some side-effect of the Add method that we don't know about (or, worse, that you don't know about), simply summing up a filtered list of Item objects might not give you the results you're looking for.

You could still use Linq:

 foreach (Loan.Fee.Item currentFee in loan.Item.Fees.Where(x => x.Classification == 806)
 {
    class806.Add(currentFee);
 }
 return class806.Sum(x => x.Fee)

I'll confess that I'm a little perplexed by the class hierarchy implied here, though, in which the Loan.Item.Fees property is a collection of Loan.Fee.Item objects. I don't know if what I'm seeing is a namespace hierarchy that conflicts with a class hierarchy, or if you're using nested classes, or what. I know I don't like it.

Robert Rossney