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>>.

Recommended Answers

All 2 Replies

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.

commented: hits the nail on the head! +15

Thanks tinstaafl, just what I needed!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.