简体   繁体   中英

Linq calculate average,total and compare the result in query

I am having trouble in following query that how to add if else in select block also I want some better way to write the following query

var x = csvParser.ParseCsv(@"data.csv");
var unsettledCustomers = x.GroupBy(g=>g.Id).
    Select(gg =>new
    {
        Id=g.Key,
        Total=g.Sum(xx=>xx.Stake),
        Avg=g.Average(ss=>ss.Win)
    }); 
var unsettledCustomers = x.GroupBy(g => g.Id)
    .Select(g => new
    {
        Id = g.Key,
        Total = g.Sum(xx => xx.Stake),
        Avg = g.Average(ss => ss.Win),
        AvgerageBet = g.Average(ss => ss.Stake),
        UnusualBets = g.Where(bet => bet.Stake > (10 * g.Average(ss => ss.Stake))).ToList()
    });

var allUnusualBets = unsettledCustomers.SelectMany(y => y.UnusualBets);

Your posted question:

I want to identify Bets where the stake (bet) is more than 10 times higher than that customer's average bet in their betting history...

Your data where Id = the customer id. Note that there are no instances where the average bet * 10 is higher than the bet placed so there are no unusual bets in your sample data according to what you have defined in your question.

Id: 1, AverageBet: 400, AverageBetTimes10: 4000, Highest bet: 1000

Id: 2, AverageBet: 15, AverageBetTimes10: 150, Highest bet: 20

Id: 3, AverageBet: 110, AverageBetTimes10: 1100, Highest bet: 300

Id: 4, AverageBet: 237.5, AverageBetTimes10: 2375, Highest bet: 300

Id: 5, AverageBet: 73.3333333333333, AverageBetTimes10: 733.333333333333, Highest bet: 100

Id: 6, AverageBet: 162.5, AverageBetTimes10: 1625, Highest bet: 500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM