问题描述
我从一个文本文件中读取号码的列表,并在列表与LT救了他们;弦乐>
,我想这些数字转换成列表< INT>
。这些数字之间用空格隔开。以下是我试过,假设数字是字符串列表:
I read a list of numbers from a text document and saved them in a List<String>
and I am trying to convert those numbers into a List<int>
. The numbers are separated by spaces. Here is what I tried, assuming Numbers is the String list:
List<int> AllNumbers = Numbers.ConvertAll<int>(Convert.ToInt32);
当我尝试使用,这是说输入字符串的不正确的格式。
When I try to use this is says "Input string was not in a correct format."
什么是转换的正确方式列表<弦乐>
到列表< INT> ?
What is the correct way to convert a List<String>
into a List<int>
?
示例:
string numbers = File.ReadAllText("numbers.txt");
string[] allNumbers = numbers.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
List<string> List = new List<string>();
List.AddRange(allNumbers);
然后我想借此列表allNumbers并将其转换为一个整数列表。
I then want to take the List allNumbers and convert it to a List of integers.
该文本文件看起来像这样:
The text file looks like this:
10 12 01 03 22 ....等
10 12 01 03 22....ect
推荐答案
它看起来像你的数字是在的单的字符串,用空格分开如果是这样,你可以使用LINQ:
It looks like your numbers are in a single string separated by spaces if so you can use Linq:
List<int> allNumbers = numbers.Split(' ').Select(int.Parse).ToList();
如果你真的有一个名单,LT >数字已经简单:
If you really have a
List<string>
numbers already simply:
List<int> allNumbers = numbers.Select(int.Parse).ToList();
终于还是,如果每个字符串可能包含由空格分隔的多个号码:
Or finally, if each string may contain multiple numbers separated by spaces:
List<int> allNumbers = numbers.SelectMany(x=> x.Split(' ')).Select(int.Parse).ToList();
这篇关于转换列表<串GT;列出< INT>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!