具有nvarchar值的SumAsync()

时间:2016-07-28 17:42:47

标签: asp.net-mvc entity-framework linq c#-4.0 linq-expressions

我有tbl_purchase表,其中包含order_date - DateTimeprice - nvarcharpid - int等字段,要求是在图表中显示每年的总价格。所以为了得到这个价格,我决定选择SumAsync。但是,此处的问题是price字段将与$$12,234.03等一起存储在$4,453.23后面,如上所述,它是nvarchar字段。我尝试在SumAsync()内分割值,但是出现了编译错误。关于如何使用它完全空白?任何解决$并总结值的解决方法?以下是我的尝试。

ChartData.cs

public class ChartData
{
   public string period {get;set;}
   public int purchase {get;set;}
   public string purchaseAmount {get;set;}
}

控制器方法

var areaModel = new List<ChartData>();
var yearList = new string[]{'2015','2016'};
foreach (var year in yearList)
{
    int yr=Convert.ToInt32(year);
    var model = new ChartData
    {
         period = year,
         purchaseAmount=await context.tbl_purchases.Where(x=>x.order_date.Year == yr).SumAsync(x=>(long)x.price.Split('$')[1]); //shows complie error. Its expecting `long` but the conversion doesn't happen well here.
    };
    areaModel.Add(model);
}

1 个答案:

答案 0 :(得分:1)

如果计算了价格格式并且总是相同,则可以按照以下步骤计算价格:

 var price = new List<string> { "$4,000.99","$20.99","$40,000.88"};

var sum = price.AsEnumerAble().Sum(x => double.Parse(x.Replace("$", "0")));

我只需将$替换为0并计算总和。