0

Hi, in my polynomial class all the terms consist of a List of tuples (double, uint), representing the coefficient and the exponent; a real and a natural number. The +operator implementation works great, but I was wondering if I could avoid to write two times grouping.Sum(s => s.Item1) It somehow feels not good, but I can't seem find a way to circumvent it. If any LINQ guru out there, could provide me with a helping hand that would be nice! :)
Here is the code:

public static tuplePolynomial operator +(tuplePolynomial tp1, tuplePolynomial tp2)
        {
            tuplePolynomial Result = new tuplePolynomial();           
            Result.Terms =
            (
                from t in tp1.Terms.Concat(tp2.Terms)
                group t by t.Item2 into grouping
                where grouping.Sum(s => s.Item1) != 0.0
                select new Tuple<double, uint>(grouping.Sum(s => s.Item1), grouping.Key)
            ).ToList();           
            return Result;
        }

I actually merge the two polymonial's terms and group the terms with the same exponents to sum them. I filter out the terms with zero exponents. Terms is of type List<Tuple<double,uint>>.

2
Contributors
2
Replies
22
Views
2 Years
Discussion Span
Last Post by ddanbe
1

Have you tried assigning grouping.Sum(s => s.Item1) to a variable, something like this?:

public static tuplePolynomial operator +(tuplePolynomial tp1, tuplePolynomial tp2)
{
    tuplePolynomial Result = new tuplePolynomial();
    Result.Terms =
    (
        from t in tp1.Terms.Concat(tp2.Terms)
        group t by t.Item2 into grouping
        let groupingsum = grouping.Sum(s => s.Item1)
        where groupingsum != 0.0
        select new Tuple<double, uint>(groupingsum, grouping.Key)
    ).ToList();
    return Result;
}

This way you only call it once.

Edited by tinstaafl

Votes + Comments
hits the nail on the head!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.