如何将 lambda 中的字符串转换为十进制?

发布于 2024-11-29 12:38:09 字数 459 浏览 0 评论 0原文

我有代码

    myEntities db = new myEntities();
    var query = from s in db.mytable select s;
    if (!String.IsNullOrEmpty(str))
    {
      query = query.Where(p => p.total == str);
    }

Here,“total”的类型是包含数字和字符的字符串,例如“14x56xz”。我想从“total”字符串中获取数字部分(例如1456)并将其转换为十进制数,有时需要将其转换为负数,使代码如下所示:

    query = query.Where(10 <= p => p.total <= 1000);

我编写了一个类处理它,但我不知道如何在Linq中调用这个处理方法。

I have the code

    myEntities db = new myEntities();
    var query = from s in db.mytable select s;
    if (!String.IsNullOrEmpty(str))
    {
      query = query.Where(p => p.total == str);
    }

Here, the type of "total" is a string containing numbers and characters, e.g. "14x56xz". I want to get the number part (e.g. 1456) from the "total" string and convert it to a decimal number, sometimes with the need to turn it into a negative number, making the code look like this:

    query = query.Where(10 <= p => p.total <= 1000);

I have written a class to process it, but I don't know how to invoke this processing method in Linq.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情感失落者 2024-12-06 12:38:09

只需在 lambda 中解析它即可。例如:

query = query.Where(10 <= p => decimal.Parse(p.total) <= 1000m);

当然,如果有任何方法可以改进数据模型,以便将逻辑数值存储为数字,那就更好了......

编辑:我想你会有在 LINQ to Entities 中将“14x56xz”转换为 1456 很困难。您也许可以在数据库端执行某些操作,以使用转换和正则表达式等公开计算列,但我不确定您是否能够以适当转换的方式在 LINQ 中表达这一点。

Just parse it in the lambda. For example:

query = query.Where(10 <= p => decimal.Parse(p.total) <= 1000m);

Of course, if there's any way you can improve your data model so that logically-numeric values are stored as numbers, that would be even better...

EDIT: I think you'll have a hard time converting "14x56xz" to 1456 in LINQ to Entities. You may be able to do something at the database side to expose a computed column using conversions and regular expressions etc, but I'm not sure that you'd be able to express that in LINQ in a way which will be converted appropriately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文