Search code examples
linqcountaggregateweighting

Linq operator to aggregate matching value and weight them


Working code.

  double[] confirmingList = new double[] { -3, -2, -1 };
    
    var Tdb = rDatas
        .Select(d => new
        {
            TScore = (new List<double> {
                d.T15Min, // Let this count .2
                d.T30Min, // .25
                d.T65Min, // .3
                d.T130Min, // .4
                d.T195Min, // .5
                d.TDaily,  // .8
                d.TWeekly // 1
                }).Count(c => confirmingList.Contains(c))

What I want is to aggregate by time frame match and weighting by property. Is there some Linq Kung Fu that does that? Should I have some class that I pass to multiply weighting by property name? I suspect there is something in the aggregate operator that would allow for this?

Can't really find something that shows a logical operation match while aggregating values with a modification or weighting.


Solution

  • Using the indexed Select method, you can match each timeframe to its weight when it should be counted:

    double[] confirmingList = new double[] { -3, -2, -1 };
    var weights = new[] { 0.2, 0.25, 0.3, 0.4, 0.5, 0.8, 1.0 };
    
    var Tdb = rDatas
        .Select(d => new {
            TScore = (new[] {
                d.T15Min, // Let this count .2
                d.T30Min, // .25
                d.T65Min, // .3
                d.T130Min, // .4
                d.T195Min, // .5
                d.TDaily,  // .8
                d.TWeekly // 1
                }).Select((t,i) => confirmingList.Contains(t) ? weights[i] : 0).Sum()
        });