选择已解析的 int,如果字符串可解析为 int [英] Select parsed int, if string was parseable to 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?
的方法:
Alternatively, you may find it worth writing a method which returns an int?
:
public static int? NullableTryParseInt32(string text)
{
int value;
return int.TryParse(text, out value) ? (int?) value : null;
}
然后你可以使用:
var ints = from str in strings
let nullable = NullableTryParseInt32(str)
where nullable != null
select nullable.Value;
这篇关于选择已解析的 int,如果字符串可解析为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!