使用 LINQ 将字符串转换为 int 数组 [英] Convert string to int array using LINQ

查看:92
本文介绍了使用 LINQ 将字符串转换为 int 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数(tointarray)可以将字符串转换为整数数组,但是我对它不是很满意.它完成了这项工作,但必须有一种更优雅的方式来做到这一点,也许 LINQ 可以在这里帮助.不幸的是,我在 LINQ 方面不是很好.有没有更好的办法?

I have a function (tointarray) to convert a string into an array of ints, but I am not very satisfied with it. It does the job, but there must be a more elegant way to do this, and perhaps LINQ could help here. Unfortunately I am not very good in LINQ. Is there a better way?

我的功能:

{
    string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
    int[] ia = tointarray(s1, ';');
}
int[] tointarray(string value, char sep)
{
    string[] sa = value.Split(sep);
    int[] ia = new int[sa.Length];
    for (int i = 0; i < ia.Length; ++i)
    {
        int j;
        string s = sa[i];
        if (int.TryParse(s, out j))
        {
            ia[i] = j;
        }
    }
    return ia;
}

推荐答案

这个帖子问了一个类似的问题,并用LINQ解决了它,也许它也能帮到你.

This post asked a similar question and used LINQ to solve it, maybe it will help you out too.

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();

这篇关于使用 LINQ 将字符串转换为 int 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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