Home > Mobile >  Percent of Yes in Yes/No column in Linq
Percent of Yes in Yes/No column in Linq

Time:10-17

I'm trying to get the percent of Yes in a Yes/No column in Linq, I have a computed column in my SQL table called CloseRed

I have a StatsBuilder class that gets the stats for each stock:

 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.FirstHigh).Average());
        allstock.AvgLow = Math.Round(stocks.Select(x => x.MorningLow).Average());

         allstock.CloseRed = Math.Round((decimal)stocks.Count(x => x.CloseRed.Contains("Yes")) / stocks.Count(x => x.CloseRed)* 100,2);

        return allstock;
    }

Obbviously my allstock.CloseRed Linq statement is incorrect but I have been un able to get it right

Thanks for the help!!

CodePudding user response:

Contains is for comparing with an enumerable, but you are comparing against a specific value, so use equality (==)

Ensure that you work in decimal for each component part. You are working with integer (Count) for the denominator.

Something like this should work:

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var theList = new List<string>{
            "yes",
            "yes",
            "yes",
            "yes",
            "yes",
            "yes",
            "no",
            "no",
            "no"
        };
        
        decimal thePercent = ((decimal)theList.Count(i => i == "yes") / (decimal)theList.Count()) * 100;
        Console.WriteLine(thePercent);
    }
}

Output:

66.666666666666666666666666670

See: https://dotnetfiddle.net/xuxKAj

  • Related