开发者

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

开发者 https://www.devze.com 2022-12-08 12:28 出处:网络
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)

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.Classi开发者_Go百科fication == 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?


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();


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.


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

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号