Home > Software engineering >  Find the Average of negative numbers in a column containing Negative and positive numbers using LINQ
Find the Average of negative numbers in a column containing Negative and positive numbers using LINQ

Time:10-28

I have a column in my database that has positive and negative numbers and I'm trying to get the Average of the negative numbers

I have a StatsBuilder Class

public class StatsBuilder
{
    private IRepository _statsRepository;
    private IEnumerable<Stock> stocks;

    public StatsBuilder()
    {
        var db = new AppDbContext();
        _statsRepository = new StockRepository(db);
    }

    public AllStockStats GetAllStats()
    {
        stocks = _statsRepository.GetAllStocks();
       

       AllStockStats allstock = new AllStockStats();

        allstock.AvgPmGap = Math.Round(stocks.Select(x => x.GapPercent).Average());
        allstock.AvgPmFade = Math.Round(stocks.Select(x => x.PMFadePercent).Average());
        allstock.AvgSpike = Math.Round(stocks.Select(x => x.SpikePercent).Average());
        allstock.AvgLow = Math.Round(stocks.Select(x => x.MorningLowPercent).Average());
        allstock.AvgClosevHigh = Math.Round(stocks.Select(x => x.ClosevHigh).Average());
        allstock.AvgClosevPmHigh = Math.Round(stocks.Select(x => x.ClosevPmHigh).Average());

        allstock.UnderPmHigh = Math.Round((decimal)stocks.Where(x => x.PmHighvHigh > 0).Count()/stocks.Count()*100);

        allstock.AbovePmHigh - Math.Round((decimal)stocks.Where(x => x.PmHighvHigh<0).Average());

        allstock.CloseRed = Math.Round(((decimal)stocks.Where(x => x.CloseRed.ToString() == "Yes").Count()) / stocks.Count() * 100);
        allstock.ClosevPmHigh = Math.Round(((decimal)stocks.Where(x => x.CloseLessEqualToPMHigh.ToString() == "Yes").Count()) / stocks.Count() * 100);


        return allstock;
    }

I'm getting an error with the Linq here

allstock.AbovePmHigh = Math.Round((decimal)stocks.Where(x => x.PmHighvHigh<0).Average());

Thanks for the help!!

CodePudding user response:

You have to select what you want to average:

allstock.AbovePmHigh = Math.Round((decimal)stocks.Where(x => x.PmHighvHigh<0).Select(x => x.PmHigjvHigh).Average());
  • Related