选择解析INT,如果字符串是解析的为int [英] Select parsed int, if string was parseable to int

查看:227
本文介绍了选择解析INT,如果字符串是解析的为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个的IEnumerable<字符串方式> 可包含可解析为 INT 即不能价值观,以及价值观

So I have an IEnumerable < string > which can contain values that can be parsed as int, as well as values that cannot be.

如你所知, Int32.Parse 抛出一个异常,如果字符串不能改变为int,而 Int32.TryParse 可以用来检查,看看是否未经处理的异常的转化是可能的。

As you know, Int32.Parse throws an exception if a string cannot be changed to an int, while Int32.TryParse can be used to check and see if the conversion was possible without dealing with the exception.

所以我想使用LINQ查询到单行解析那些可以被解析为int的字符串,不一路上抛出异常。我有一个解决方案,但是会从社区希望指教一下这是否是最好的办法。

So I want to use a LINQ query to one-liner parse those strings which can be parsed as int, without throwing an exception along the way. I have a solution, but would like advice from the community about whether this is the best approach.

下面是我有:

int asInt = 0;

var ints = from str in strings
           where Int32.TryParse(str, out asInt)
           select Int32.Parse(str);

因此​​,大家可以看到,我使用的是'asInt作为呼叫的TryParse一个暂存空间,只是确定的TryParse会成功(返回布尔)。然后,在投影,我实际进行解析。那种感觉难看。

So as you can see, I'm using 'asInt' as a scratch space for the call to TryParse, just to determine if TryParse would succeed (return bool). Then, in the projection, I'm actually performing the parse. That feels ugly.

这是筛选使用LINQ在一个在线的解析的值的最佳方式是什么?

Is this the best way to filter the parseable values in one-line using LINQ?

推荐答案

这是很难做到这一点的查询语法,但它不是太糟糕的lambda语法:

It's hard to do that in query syntax, but it's not too bad in lambda syntax:

var ints = strings.Select(str => {
                             int value;
                             bool success = int.TryParse(str, out value);
                             return new { value, success };
                         })
                  .Where(pair => pair.success)
                  .Select(pair => pair.value);

另外,你可能会发现它值得写它返回一个方法的 INT

public static int? NullableTryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? (int?) value : null;
}

然后,你可以使用:

Then you can just use:

var ints = from str in strings
           let nullable = NullableTryParseInt32(str)
           where nullable != null
           select nullable.Value;

这篇关于选择解析INT,如果字符串是解析的为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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