简体   繁体   中英

How to convert List<String[]> to List<int[]>?

I am trying to cast a list of string arrays to a list of int arrays. I have tried the following:

List<int[]> dataset = Read(fileName, separator).Select(
    line => Array.ConvertAll(line, s => int.Parse(s)
);

Read return a list of string array: List<String[]> dataset

You can use .ToList<T>() to convert .Select() result (which is IEnumerable<int[]> ) to a list.
This way, you apply int.Parse to every item of item array, and convert the result to List.
Also, in order to provide code homogeneity, you can use LINQ Select and ToArray instead of Array.ConvertAll :

List<string[]> stringArrayList = ...;
List<int[]> intArrayList = stringArrayList
    .Select(stringArray => stringArray.Select(int.Parse).ToArray())
    .ToList();

One little correction: you do not cast string to an int, you convert / parse it.

You can try something like this:

List<int[]> Listintegers = yourList
    .Select(y => y.Select(x => int.Parse(x)).ToArray())
    .ToList();
List<string[]> source = new List<string[]>
{
    new string[2] { "2", "3" },
    new string[4] { "4", "5", "6", "7" },
    new string[1] { "1" }
};

List<int[]> result = source.Select(array => Array.ConvertAll(array, item => int.Parse(item))).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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