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?
source to share
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.
source to share