转换列表<串GT;列出< INT>

编程入门 行业动态 更新时间:2024-10-28 10:29:36
本文介绍了转换列表<串GT;列出< INT>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从一个文本文件中读取号码的列表,并在列表与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();

更多推荐

转换列表&LT;串GT;列出&LT; INT&GT;

本文发布于:2023-11-26 22:49:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   amp   LT   GT   INT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!