C# 在实体框架 linq 查询中将字符串转换为 int 并处理解析异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12677256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:05:22  来源:igfitidea点击:

Convert string to int in an Entity Framework linq query and handling the parsing exception

c#linqentity-framework

提问by S3ddi9

I've got this problem, I have a table for purchases

我有这个问题,我有一张桌子可以买

Purchases(Date DateTime, Number string)

I want is to create a new record, so I need the Max(Number), the problem here is that Number is a string, I've tried

我想要创建一个新记录,所以我需要 Max(Number),这里的问题是 Number 是一个字符串,我试过了

Purchases.Select(X=>int.Parse(X.Number)).Max()

but it could throw an exception, I've create a custom ToInt()extension so when I use

但它可能会引发异常,我已经创建了一个自定义ToInt()扩展,所以当我使用

Purchases.Select(X=>X.Number.ToInt()).Max()

it throws an exception saying that my ToInt() can't be used with linq query same as the famous ToString()

它抛出一个异常,说我的 ToInt() 不能与著名的 ToString() 一样用于 linq 查询

so my questionis : is there a way to cast a string to int in linq query & handling exceptions at the same time or to integrate custom functions to a linq query !!

所以我的问题是:有没有办法在 linq 查询中同时将字符串转换为 int 并处理异常,或者将自定义函数集成到 linq 查询中!!

and this's my extension

这是我的扩展

    public static int ToInt(this string s)
    {
        try
        {
            return int.Parse(s);
        }
        catch
        {
        }
        return 0;
    }

采纳答案by Gromer

First way:

第一种方式:

var numbers = Purchases.Select(x => x.Number).ToList();

int temp;
int max = numbers.Select(n => int.TryParse(n, out temp) ? temp : 0).Max();

Console.WriteLine("Max: {0}", max);

Second way:

第二种方式:

int temp2;
int max2 = Purchases.Select(x => x.Number).ToList().Select(n => int.TryParse(n, out temp2) ? temp2 : 0).Max();

Console.WriteLine("Max 2: {0}", max2);

The key is the .ToList()in those two ways. It gets all the stringdata from the database, so when you call int.TryParseon the results, the database query has already been run, so it is using pure CLR code, and not trying to convert int.TryParseinto a SQL query. I made an EF context in one of my Sandbox projects and verified this works.

关键是.ToList()这两种方式。它string从数据库中获取所有数据,因此当您调用int.TryParse结果时,数据库查询已经运行,因此它使用纯 CLR 代码,而不是尝试转换int.TryParse为 SQL 查询。我在我的一个 Sandbox 项目中创建了一个 EF 上下文并验证了它的工作原理。

回答by Shahar Gvirtz

I don't understand why you don't want the exception, because if you failed the casting, then it means something wrong happened to your application (or at least, so i get it). I also don't understand why to save what supposed to be a number as a string in the database. Usually, you'll keep it as a number so you won't have to deal with problems like this later, and if someone try to insert wrong value you'll fail on insertion.

我不明白你为什么不想要这个异常,因为如果你的转换失败了,那么这意味着你的应用程序出了问题(或者至少,我明白了)。我也不明白为什么将应该是数字的内容保存为数据库中的字符串。通常,您会将它保留为一个数字,这样您以后就不必处理此类问题,如果有人尝试插入错误的值,您将无法插入。

BUT - if you do want to make this line works you should use int.TryParsewhich will return you true if the value casted successfully and will put the value in 'out' member which will be out of the query. like this:

但是 - 如果你确实想让这条线起作用,你应该使用int.TryParse它,如果值成功转换,它将返回 true 并将值放入'out'成员中,该成员将不在查询中。像这样:

int tmp;
Purchases.Select(X=>int.TryParse(X.Number, out tmp) ? tmp : 0).Max()

and instead of "0" put some default value that won't mess with your logic.

而不是“0”,而是放置一些不会干扰您的逻辑的默认值。