C#中的LINQ / Lambda表达式:如何选择一个字符串的整数? [英] C# Linq/Lambda expression: How to select an integer out of a string?
问题描述
我想解释一下我的问题的最佳方法是使用短(通用)LINQ到对象的代码示例:
I think the best way to explain my question is with a short (generic) linq-to-objects code sample:
IEnumerable<string> ReadLines(string filename)
{
string line;
using (var rdr = new StreamReader(filename))
while ( (line = rdr.ReadLine()) != null)
yield return line;
}
IEnumerable<int> XValuesFromFile(string filename)
{
return ReadLines(filename)
.Select(l => l.Substring(3,3))
.Where(l => int.TryParse(l))
.Select(i => int.Parse(i));
}
注意,这个代码解析的整数的两倍。我知道我缺少一个明显的简单的方式来消除这些电话中的一个安全的(也就是因为我以前做过)。我现在不能找到它。我怎样才能做到这一点。
Notice that this code parses the integer twice. I know I'm missing an obvious simple way to eliminate one of those calls safely (namely because I've done it before). I just can't find it right now. How can I do this?
推荐答案
我想我会像这样的东西去?
I think I'll go with something like this:
IEnumerable<O> Reduce<I,O>(this IEnumerable<I> source, Func<I,Tuple<bool, O>> transform )
{
foreach (var item in source)
{
try
{
Result<O> r = transform(item);
if (r.success) yield return r.value;
}
catch {}
}
}
ReadLines().Reduce(l => { var i; new Tuple<bool, int>(int.TryParse(l.Substring(3,3),i), i)} );
我真的不喜欢这一点,虽然,因为我已经的上的记录以这种方式不喜欢使用的元组。不幸的是,我没有看到滥用例外或限制其引用类型(其中空
被定义为失败的转换)以外的许多替代品,两者都不是好得多。
I don't really like this, though, as I'm already on the record as not liking using tuples in this way. Unfortunately, I don't see many alternatives outside of abusing exceptions or restricting it to reference types (where null
is defined as a failed conversion), neither of which is much better.
这篇关于C#中的LINQ / Lambda表达式:如何选择一个字符串的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!