我试图从像这样的通用列表中使用LINQ获取val:

private List<PriceVarianceDataAmalgamated> CombineSubsets(string unit)
{
    List<PriceVarianceDataAmalgamated> combinedSubsets = new List<PriceVarianceDataAmalgamated>();
    if (unit.Equals(CRAFTWORKS_SC))
    {
        foreach (PriceVarianceSubsetData pvsd in craftworksWeek1PVDSubsetList)
        {
            PriceVarianceDataAmalgamated pvda = new PriceVarianceDataAmalgamated
            {
                ShortName = pvsd.ShortName,
                ItemCode = pvsd.ItemCode,
                Description = pvsd.Description,
                Price1 = pvsd.Price,
                Price2 = GetPrice2(CRAFTWORKS_SC, pvsd.ShortName, pvsd.ItemCode)
            };
            pvda.Variance = "0.00";
            decimal price1 = Convert.ToDecimal(pvda.Price1);
            decimal price2 = Convert.ToDecimal(pvda.Price2);
            . . .


关键部分(无法执行我想要的操作)是对GetPrice2()的调用。该方法开始:

private string GetPrice2(string _unit, string _shortname, string _itemcode)
{
    string price2 = "0.00";
    if (_unit.Equals(CRAFTWORKS_SC))
    {
        price2 = craftworksWeek2PVDSubsetList
            .Where(x => x.ShortName.Equals(_shortname))
            .Where(x => x.ItemCode.Equals(_itemcode))
            .Select(x => x.Price).ToString();
    }
    . . .


...当我进入那里对price2的分配时,分配的val是:

System.Linq.Enumerable+WhereSelectListIterator`2[Pivotal.PriceVarianceSubsetData,System.String]


?!?

给出的错误信息为:

System.FormatException was unhandled
  HResult=-2146233033
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
       at System.Convert.ToDecimal(String value)
       at Pivotal.FormMain.CombineSubsets(String unit) in c:\Projects\PriceVariance\Pivotal\Form1.cs:line 290
       at Pivotal.FormMain.GenerateAndSaveSpreadsheetFile() in c:\Projects\PriceVariance\Pivotal\Form1.cs:line 154
       at Pivotal.FormMain.buttonRun_Click(Object sender, EventArgs e) in c:\Projects\PriceVariance\Pivotal\Form1.cs:line 137
. . .


因此,此行(290)失败:

List<PriceVarianceDataAmalgamated> pvdaCraftworks = CombineSubsets(CRAFTWORKS_SC);


...更具体地说,这一行(第154行):

decimal price2 = Convert.ToDecimal(pvda.Price2);


显然,错误的代码是这样的:

price2 = craftworksWeek2PVDSubsetList
    .Where(x => x.ShortName.Equals(_shortname))
    .Where(x => x.ItemCode.Equals(_itemcode))
    .Select(x => x.Price).ToString();


在逐步解决问题时,“ _ shortname”和“ _itemcode”均具有有效值;完全有可能没有选择的值,但是我似乎通过为price2分配默认值来对此进行辩护:

string price2 = "0.00";


在方法的最后返回了price2-也许我应该使用catch块并在那里分配后备值,而不是从git-go中返回?

最佳答案

使用

.Select(x => x.Price).FirstOrDefault().ToString();


不会引发异常,而是为引用类型返回空值,为值类型返回默认值。可能使您更容易找到问题所在

关于c# - 为什么此LINQ抛出“未处理FormatException”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38214007/

10-09 10:15