无法转换类型' System.Data.EnumerableRowCollection`1 [System.String]'键入' System.IConvertible'

时间:2016-12-14 02:27:32

标签: c# linq

我需要通过LINQ获取数据表(驻留在数据集中)的列值(FundSpreadDurationContribution),获取上述错误(标题)

详细说明:当行单元格具有值 Spread Duration - IR Swap 时,需要相应的列单元 FundSpreadDurationContribution 值。

 double testvalue = Convert.ToDouble(raptorDS.Tables[RaptorTable.DurationContribBySector].AsEnumerable().Where(r =>
                                         r.Field<string>(RaptorColumns.FundCode) == fundDescriptionColumn &&
                                         r.Field<string>(RaptorColumns.Component) == Component.B8_DURATION_CONTRIBUTION_BY_SECTOR &&
                                         r.Field<string>(RaptorColumns.Sector) == "Spread Duration--IR Swap").Select(s => s.Field<string>(RaptorColumns.FundSpreadDurationContribution)))

我是LINQ的学习者。

3 个答案:

答案 0 :(得分:1)

Where返回一个无法转换为double的集合。使用其中一个Linq方法获得一个转换答案:

  • Single
  • SingleOrDefault
  • First
  • FirstOrDefault

答案 1 :(得分:1)

// First check if this query will return any results 
var records =
    raptorDS.Tables[RaptorTable.DurationContribBySector].AsEnumerable().Where(r =>
    r.Field<string>(RaptorColumns.FundCode) == fundDescriptionColumn &&
    r.Field<string>(RaptorColumns.Component) == Component.B8_DURATION_CONTRIBUTION_BY_SECTOR &&
    r.Field<string>(RaptorColumns.Sector) == "Spread Duration--IR Swap");

// CHeck if any result
if (records.Any())
{
    // We have results so let's go through each record and try to get that value
    // converted to a double
    List<double> values = new List<double>();
    List<string> badValues = new List<string>();
    foreach (var thisRecord in records)
    {
        var fsdc = thisRecord.Field<string>(RaptorColumns.FundSpreadDurationContribution);
        if (!string.IsNullOrWhiteSpace(fsdc))
        {
            double val = 0;
            if (double.TryParse(fsdc, val))
            {
                values.Add(val);
            }
            else
            {
                badValues.Add(fsdc);
            }
        }
    }

    // Do whatever you need to do with values here

    // and bad values here
}

答案 2 :(得分:0)

这只是解决了修复类型转换问题的数据类型

 var sumFundSpreadDuration = raptorDS.Tables[RaptorTable.DurationContribBySector].AsEnumerable().Where(r =>
                                             r.Field<string>(RaptorColumns.FundCode) == fundDescriptionColumn &&
                                             r.Field<string>(RaptorColumns.Component) == Component.B8_DURATION_CONTRIBUTION_BY_SECTOR &&
                                             r.Field<string>(RaptorColumns.Sector) == "Spread Duration--IR Swap")
                                             .Select(s => s.Field<double?>(RaptorColumns.FundSpreadDurationContribution)).FirstOrDefault();

如果您看到变量的数据类型从double更改为Variant。此外,列FundSpreadDurationContribution的数据类型更改为double。感谢CodingYoshi提供了linq

中数据类型的见解