Simplify and design linq queries

In my new project I am writing a lot of linq. And I have a lot of linq queries, like this:

...
group new {A, B} by new {....}
into g
// Calculate select claw
let SumVal1 = g.Sum(x => x.A.Value1 * func(x.A, x.B)) / g.Sum(x => func(x.A, x.B))
let SumVal2 = g.Sum(x => x.A.Value2 * func(x.A, x.B)) / g.Sum(x => func(x.A, x.B))
let SumVal3 = g.Sum(x => x.A.Value3 * func(x.A, x.B)) / g.Sum(x => func(x.A, x.B))
....
// Here could be some calculation, that are not patterned, like:
let NotPatternedSum1 = g.Sum(x => x.A.Duration)
...
select new {SumVal1, SumVal2, SumVal3, ..., NotPatternedSum, ...}

How can I simplify this? I have many requests with this template (Sum (A * func) / Sum (func)) - how can I present this to a single method or delegate?

Perhaps you saw some tips for developing large linq queries? My code consists of 95% linq (I will move on to the db logic for the client). Pls give me some tips, maybe nontrivial =)

And I want to avoid using non-anonymous types

+3
source share
1 answer

- ( int , , - , ).

public static int DividingSum<T>(this IEnumerable<T> source,
    Func<T, int> f1, Func<T, int> f2)
{
    return source.Sum(t => f1(t) * f2(t)) / source.Sum(t => f2(t));
}

, , f1 f2, :)

:

let SumVal1 = g.DividingSum(x => x.A.Value1, func)

LINQ ... LINQ to SQL ( Entities) , , , .

EDIT: , :

let SumVal1 = g.DividingSum(x => x.A.Value1, x => func(x.A, x.B))
+4

Source: https://habr.com/ru/post/1760524/


All Articles