Can I use linq to achieve the same as this foreach loop does?

Here is the C # code 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 with linq? If so, how? I've never used linq, and I've read in several places that using linq instead of a foreach loop is faster ... is it true?

+2


source to share


5 answers


As in some of the existing answers, but by doing the projection in the request, making the call is Sum

much easier:



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

      

+4


source


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, non-LINQ version could be faster.

+4


source


var q =
  from currentFee in loan.Item.Fees
  where currentFee.Classification == 806
  select currentFee;

var sum = q.Sum(currentFee => currentFee.Fee); 

      

+2


source


private double get806Fees(Loan loan)
{
    return load.Item.Fees.
        Where(f => f.Classification == 806).
        Sum(f => f.ValueToCalculateSum);
}

      

I guess it is ValueToCalculateSum

also double. If it is not, you need to convert it before it is returned.

+1


source


All answers so far assume you are summarizing loan.Fees

. But the code you actually posted calls Items.Add()

to add each Item

in loan.Fees.Items

to an object Items

, and that's the object Items

(and not loan.Fees

which is also an object Items

)) that you say you want to summarize.

Now, if Items

is just a simple collection class, then there is no need to do anything other than what people suggest here. But if there is some side effect of the method Add

that we don't know about (or worse, that you don't know about), simply summing the filtered list of objects Item

may not give you the results you are looking for.

You can 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 confess that I am a bit confused by the class hierarchy implied here, even though a property Loan.Item.Fees

is a collection of objects Loan.Fee.Item

. I don't know if what I see is a namespace hierarchy that conflicts with the class hierarchy, or if you are using nested classes or what. I know I don't like this.

0


source







All Articles