我試圖在 Linq 的 Yes/No 列中獲取 Yes 的百分比,我的 SQL 表中有一個計算列,名為 CloseRed
我有一個 StatsBuilder 類,用于獲取每只股票的統計資訊:
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;
}
顯然我的 allstock.CloseRed Linq 宣告是不正確的,但我一直無法做到正確
謝謝您的幫助!!
uj5u.com熱心網友回復:
Contains用于與可列舉進行比較,但您正在與特定值進行比較,因此請使用等式 ( ==)
確保您對每個組成部分使用十進制。您正在使用整數 ( Count) 作為分母。
這樣的事情應該作業:
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);
}
}
輸出:
66.666666666666666666666666670
請參閱:https : //dotnetfiddle.net/xuxKAj
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323859.html
