我Convert.ToDecimal在 linq 中使用,有時金額值以點 (.) 形式出現,因為用戶可能想要寫.50或其他內容,一旦他們輸入(使用來自移動設備的數字鍵盤)值,代碼就會被執行并拋出exception.
我正在獲取string is not correct format exception以下代碼
var enteredAmountInTenders = TenderListCollection.Sum(x => Convert.ToDecimal(string.IsNullOrEmpty(x.Amount) ? "0" : x.Amount));
我怎樣才能忽略上面代碼的點而只得到 0?
uj5u.com熱心網友回復:
我會使用decimal.TryParse而不是Convert.ToDecimal轉換值。
var enteredAmountInTenders = TenderListCollection
.Sum(x => !decimal.TryParse(x.Amount,out var result) ? 0 : result);
uj5u.com熱心網友回復:
您可以在為TenderListCollection.
private string _amount = "0";
public string Amount
{
get
{
return _amount;
}
set
{
if(!string.IsNullOrEmpty(value))
{
if(value != ".")
{
_amount = value;
}
}
}
}
一般來說,我不喜歡將金額存盤為字串,所以我也建議將金額重命名為GivenAmount并具有一個小數的金額屬性,這樣我們的代碼就很干凈,您不需要決議 Lambda 運算式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/414422.html
標籤:
上一篇:LINQToEntity-LINQtoEntities無法識別方法“DoubleParse(System.String)”方法
