Reputation: 63
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
Upvotes: 2
Views: 3221
Reputation: 86
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();
Upvotes: 0
Reputation: 120
You can try something like this:
List<int[]> Listintegers = yourList
.Select(y => y.Select(x => int.Parse(x)).ToArray())
.ToList();
Upvotes: 0
Reputation: 34244
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.
Upvotes: 3