在Linq中字符(字符串)编码的数字到数字的比较

本文关键字:数字 编码 比较 字符串 Linq 字符 | 更新日期: 2023-09-27 18:11:26

我有这个查询。

  levelnumber = (from b in bv.baLevels
                 where b.ba_Level_Code == ("0" + SqlFunctions.StringConvert((double)cl.Level_Num.Value)) && b.isActive == 1
                 select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(),

我的问题是b.b.ba_level_code是字符串。

cl。Level_Num是Int

ba_Level_code的值是008

但是cl是bacodelbrary表。Level_Num有8

如果我使用硬编码值

进行查询
 levelnumber = (from b in bv.baLevels
                where b.ba_Level_Code == "008" && b.isActive == 1
                select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(),

如何显示008?cl。我得到的Level_Num是8。我需要将该值更改为008。

谢谢

在Linq中字符(字符串)编码的数字到数字的比较

我看不出在LINQ to entities中这样做的好方法。假设您不能修改ba_Level_Code列的数据类型,我认为您最好的选择是向该表添加一个持久化计算列,对其建立索引,并在查询中使用该列。

例如,如果您定义了一个列

ba_Level_Code_Int as (case when isnumeric(ba_Level_Code)= 1 then cast(ba_Level_Code as int) end) persisted

那么你的LINQ查询可以是

levelnumber = (from b in bv.baLevels   
               where b.ba_Level_Code_Int == cl.Level_Num.Value && b.isActive == 1   
               select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault();

您可以使用string.Format来指定您的' cl。将Level_Num'转换为具有最小位数的字符串:

string.Format("{0:D3}", cl.Level_Num.Value) // would ouput "008" value 8

:

levelnumber = (from b in bv.baLevels
               where b.ba_Level_Code == string.Format("{0:D3}", cl.Level_Num.Value) && b.isActive == 1
               select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault()