将Entity Framework LINQ查询中的字符串转换为int,并处理解析异常 [英] Convert string to int in an Entity Framework linq query and handling the parsing exception

查看:97
本文介绍了将Entity Framework LINQ查询中的字符串转换为int,并处理解析异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,我有一张购买表

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

Purchases(Date DateTime, Number string)

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

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

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

但它可能会抛出异常,创建自定义 ToInt()扩展名,所以当我使用

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

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

它抛出一个例外说我的ToInt()不能与linq查询一样使用与着名的ToString()

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

所以我的问题是:是有一种方法可以在linq query&同时处理异常或将自定义函数集成到一个linq查询中!!

so my question is : 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 !!

这是我的扩展名

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


推荐答案

第一种方式:

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);

第二种方式:

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);

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

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

这篇关于将Entity Framework LINQ查询中的字符串转换为int,并处理解析异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆