简体   繁体   English

如何将 string[] 转换为列表<int> ?

[英]How I can convert string[] to list<int>?

How I can convert an array of strings to list of int?如何将字符串数组转换为 int 列表? (without converting them one by one with my own method) (没有用我自己的方法一一转换)

From searching in google I've seen methods named ToList() and ConvetAll() but I cant typed them, why is that?通过在 google 中搜索,我看到了名为 ToList() 和 ConvetAll() 的方法,但我无法输入它们,这是为什么?

What I've tried is:我试过的是:

new list<int>((int[])s.Split(','));

and I'm getting error that i cant convert string[] to int[] :(我收到错误,我无法将 string[] 转换为 int[] :(

There's a two-step process involved here.这里涉及一个两步过程。 The first is to convert the strings to an integer, then convert the array to a list.首先是将字符串转换为整数,然后将数组转换为列表。 If you can use LINQ, the easiest way is to use:如果可以使用LINQ,最简单的方法是使用:

stringArray.Select(x => Int32.Parse(x)).ToList();

从您的代码中获取提示:

var listOfInts = s.Split(',').Select(Int32.Parse).ToList();

Try Using尝试使用

int x = 0; 

var intList= stringList.Where(str => int.TryParse(str, out x)).Select(str => x).ToList();
public List<int > M1()
{
    string[] s =(file path));
    Array.Sort(s);
    var c = new List<int>();
    foreach(string x in s)
    {
        c.Add(Convert.ToInt32(x));
    }
    return c;
}

use following:使用以下:

var list = s.Select(Int32.Parse).ToList(); var list = s.Select(Int32.Parse).ToList();

Try it:尝试一下:

 var selectedEditionIds = input.SelectedEditionIds.Split(",").ToArray()
                        .Where(i => !string.IsNullOrWhiteSpace(i) 
                         && int.TryParse(i,out int validNumber))
                        .Select(x=>int.Parse(x)).ToList();

For VB.NET, I had to do it in a loop对于 VB.NET,我必须循环执行

Dim myList As New List(Of Integer)
For Each item As String In s.Split(",")
    myList.Add(Val(item))
Next

May have been able to work it out with some inbuilt function but didn't want to spend too much time on it.可能已经能够使用一些内置函数来解决它,但不想花太多时间在上面。

Assuming values is your list of strings:假设values是您的字符串列表:

int[] ints = new int[values.Count];

int counter = 0;
foreach (string s in values) {
    ints[counter++] = int.Parse(s);
}

Don't overcomplicate yourself :)不要让自己过于复杂:)

var s = "1,2,3,4,5,6,7,8,9";
var result = s.Split(',').Select(Convert.ToInt32).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM