拆分字符串并在选择计算中使用

时间:2016-05-29 12:58:58

标签: c# linq linq-to-sql

我试图拆分一个字符串字段并在Select new中使用计算中的值,这样我就可以在报表中显示该信息。计算是针对包装的立方米。以下代码是我现在使用的代码,但是当我尝试将分割字符串中的值相乘时,我得到一个错误:

  

无法翻译表达式' Parse(grp.Key.Length)'进入SQL并且不能将其视为本地表达式

 var res = (from packs in data
            where packs.DispatchDate != null || (packs.DispatchDate >= DateTime.Parse(_dateFrom).Date &&
            packs.DispatchDate <= DateTime.Parse(_dateTo).Date)
            orderby packs.Production.DimensionMetric
            group packs by
            new
            {
                 packs.DispatchDate,
                 packs.ProductType.TypeDetails,
                 packs.PackNo,
                 packs.Thickness,
                 Width = packs.Production.DimensionMetric.Substring(0,packs.Production.DimensionMetric.IndexOf('x')),
                 Length = packs.Production.DimensionMetric.Substring(packs.Production.DimensionMetric.IndexOf('x')+1),
                          packs.Sheets,
            }
            into grp
            select new
            {
                 grp.Key.DispatchDate,
                 grp.Key.TypeDetails,
                 grp.Key.PackNo,
                 grp.Key.Thickness,
                 grp.Key.Width,
                 grp.Key.Length,
                 grp.Key.Sheets,
                 CBM = ((int.Parse(grp.Key.Length)) * (int.Parse(grp.Key.Length))).ToString(),
             }).ToList();

如果我只是将长度和宽度的值分配或连接到CBM,则没有错误,仅当我对2个值执行数学计算时才会出现错误。有人可以解释为了使这项工作需要做些什么,还是我必须从另一个角度来看待它?

1 个答案:

答案 0 :(得分:1)

 var res = (from packs in data
        where packs.DispatchDate != null || (packs.DispatchDate >= DateTime.Parse(_dateFrom).Date &&
        packs.DispatchDate <= DateTime.Parse(_dateTo).Date)
        orderby packs.Production.DimensionMetric
        group packs by
        new
        {
             packs.DispatchDate,
             packs.ProductType.TypeDetails,
             packs.PackNo,
             packs.Thickness,
             Width = packs.Production.DimensionMetric.Substring(0,packs.Production.DimensionMetric.IndexOf('x')),
             Length = packs.Production.DimensionMetric.Substring(packs.Production.DimensionMetric.IndexOf('x')+1),
                      packs.Sheets,
        }
        into grp
        select grp)
         .AsEnumerable()
         .Select(x=>new {
             x.Key.DispatchDate,
             x.Key.TypeDetails,
             x.Key.PackNo,
             x.Key.Thickness,
             x.Key.Width,
             x.Key.Length,
             x.Key.Sheets,
             CBM = ((int.Parse(x.Key.Length)) * (int.Parse(x.Key.Length))).ToString(),
   })
   .ToList();