如何将分隔的字符串 split() 为 List<String> [英] How to split() a delimited string to a List<String>
本文介绍了如何将分隔的字符串 split() 为 List<String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码:
String[] lineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
lineElements = line.Split(',');
. . .
但后来想我也许应该用 List 代替.但是这段代码:
but then thought I should maybe go with a List instead. But this code:
List<String> listStrLineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
listStrLineElements = line.Split(',');
. . .
...给我,不能将类型‘string[]’隐式转换为‘System.Collections.Generic.List’"
推荐答案
string.Split()
返回一个数组 - 您可以使用 ToList()
将其转换为列表>:
string.Split()
returns an array - you can convert it to a list using ToList()
:
listStrLineElements = line.Split(',').ToList();
注意需要导入System.Linq
才能访问.ToList()
函数.
Note that you need to import System.Linq
to access the .ToList()
function.
这篇关于如何将分隔的字符串 split() 为 List<String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文