7

可能重复:
LINQ:选择已解析的 int,如果字符串可解析为 int

这可能是一个基本问题,但我无法找到解决方法。我有一个字符串数组,我试图用整数解析它们。正如预期的那样,我得到了格式异常。

我怎样才能跳过“3a”并继续解析剩余的数组并使用 Linq 将整数存储到输出中。?这是更好的方法还是不做的做法?请阐明在这种情况下如何使用 TryParse

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] values = { "1", "2", "3a","4" };
            List<int> output = new List<int>();

            try{
                output = values.Select(i => int.Parse(i)).ToList<int>();
            }
            catch(FormatException)
            {
                foreach (int i in output)
                    Console.WriteLine(i);
            }

            foreach (int i in output)
                Console.WriteLine(i);

            Console.ReadLine();
        }

    }
}
4

6 回答 6

7

您可以使用int.TryParse

string[] values = { "1", "2", "3a","4" };
int i = int.MinValue;
List<int> output = values.Where(s => int.TryParse(s, out i))
                         .Select(s => i)
                         .ToList();

演示

然而,Eric Lippert不会被逗乐。因此,如果您不想(ab)使用副作用,这将是最佳实践方法:

创建一个扩展方法,如:

public static class NumericExtensions
{
    public static int? TryGetInt(this string item)
    {
        int i;
        bool success = int.TryParse(item, out i);
        return success ? (int?)i : (int?)null;
    }
}

然后你可以这样写:

List<int> output = values.Select(s => s.TryGetInt())
             .Where(nullableInt => nullableInt.HasValue)
             .Select(nullableInt => nullableInt.Value)
             .ToList();
于 2013-01-22T13:10:14.633 回答
2

来自Tim Schmelter回答的 linq 版本

        string[] values = { "1", "2", "3a", "4" };
        int i = int.MinValue;
        var output = (from c in values
                      where int.TryParse(c, out i) 
                      select c).Select(s => int.Parse(s)).ToList();
        foreach (var item in output)
        {
            Console.WriteLine(item.ToString());
        }
于 2013-01-22T13:37:58.140 回答
2

尽管我完全同意int.TryParse在 Tim Schmelter 的回答中使用 ,但我认为他的回答依赖于未记录的实现细节,更安全的替代方案可能是

List<int> output =
    values
    .Select(s => {
        int i;
        return int.TryParse(s, out i) ? i : default(int?);
    })
    .Where(i => i != null)
    .Select(i => i.Value)
    .ToList();

您也许可以将 替换.Where(...).Select(...).OfType<int>()

您也可以将第一个.Select(...)lambda 表达式与显式的可重用函数放在一起:

int? MyTryParse(string s)
{
    int i;
    return int.TryParse(s, out i) ? i : default(int?);
}

List<int> output =
    values
    .Select(MyTryParse)
    .Where(i => i != null)
    .Select(i => i.Value)
    .ToList();
于 2013-01-22T13:25:29.087 回答
1

这个怎么样?受蒂姆的回答启发,但临时变量在循环内移动,因此它是并行安全的(假设字符串集合values是 ParallelEnumerable)。

values.Select(s =>
    {int i; return int.TryParse(s, out i) ? (int?)i : null;})
    .Where(x=>x!=null).Select(x=>x.Value);

所以鉴于["1", "two", "3"]它返回[1,3]

于 2013-01-22T13:29:54.163 回答
1

为什么要使用 LINQ?

尝试这个:

foreach(string str in values)
{
   int val;
   if(int.TryParse(str, out val))
   {
      output.Add(val);
   }
}
于 2013-01-22T13:17:23.467 回答
0
List<string> output = values.Where(v => Regex.Match(v, "^(0|[1-9][0-9]*)$").Success)
                                        .ToList();

使用 Regex 进行更多控制以指示哪些值被视为有效的示例。

于 2013-01-22T13:20:38.907 回答