c# - 在 linq 中使用 out 类型

标签 c# .net linq

<分区>

Possible Duplicate:
LINQ: Select parsed int, if string was parseable to 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();
        }

    }
}

最佳答案

您可以使用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();

Demo

但是,Eric Lippert would not be amused .因此,如果您不想(滥用)使用副作用,这将是最佳实践方法:

创建一个扩展方法,如:

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

关于c# - 在 linq 中使用 out 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459311/

相关文章:

C# Linq to XML 添加、更新、删除

c# - NUnit属性

c# - 有没有办法使用 linq 遍历对象列表的属性?

c# - 如何将 linq 查询绑定(bind)到转发器?

c# - 命名空间名称存在于树中的两个点是否可以?

c# - 当 URL 包含特定查询参数时,如何绕过所有其他 MVC 路由?

c# - 检查变量何时等于另一个值的更好方法

mysql - ASP.NET MySQL openauth 不工作

c# - 是否可以创建与所用键盘相同的键盘布局?

c# - linq toentity datediff 单元测试失败,但 sql 数据失败