vb.net 是否有等效于 String.Split 的返回通用列表的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/201607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:51:05  来源:igfitidea点击:

Is there an equivalent to String.Split that returns a generic list?

vb.netgenerics

提问by Herb Caudill

I'd like to do something like this:

我想做这样的事情:

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)

Of course Foo.Splitreturns a one-dimensional array of String, not a generic List. Is there a way to do this without iterating through the array to turn it into a generic List?

当然Foo.Split返回一个一维数组String,而不是一个泛型List。有没有办法在不遍历数组的情况下将其转换为泛型List

回答by Bob King

If you don't want to use LINQ, you can do:

如果您不想使用 LINQ,可以执行以下操作:

Dim foo As String = "a,b,c,d,e"
Dim boo As New List(Of String)(foo.Split(","c))

回答by Mats Fredriksson

You can use the List's constructor.

您可以使用 List 的构造函数。

String foo = "a,b,c,d,e";
List<String> boo = new List<String>(foo.Split(","));

回答by Jon Skeet

Do you really need a List<T> or will IList<T> do? Because string[] already implements the latter... just another reason why it's worth programming to the interfaces where you can. (It could be that in this case you really can't, admittedly.)

你真的需要 List<T> 还是 IList<T> 会做?因为 string[] 已经实现了后者......这是值得对接口进行编程的另一个原因。(诚​​然,在这种情况下,您可能真的不能。)

回答by amcoder

The easiest method would probably be the AddRange method.

最简单的方法可能是 AddRange 方法。

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String)

Boo.AddRange(Foo.Split(","c))

回答by mattruma

Here is how I am doing it ... since the split is looking for an array of char I clip off the first value in my string.

这是我的做法......因为拆分正在寻找一个字符数组,所以我剪掉了字符串中的第一个值。

var values = labels.Split(" "[0]).ToList<string>();

回答by Gopher

To build on the answer, Ive found the following very helpful:

为了建立在答案的基础上,我发现以下内容非常有帮助:

Return New List(Of String)(IO.File.ReadAllLines(sFileName))

回答by Tim Makins

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String)
Boo = Split(Foo, ",").ToList

The advantage of doing it this way is that the split-string will accept multiple characters:

这样做的好处是拆分字符串将接受多个字符:

Dim Foo as String = "a<blah>b<blah>c<blah>d<blah>e"
Dim Boo as List(of String)
Boo = Split(Foo, "<blah>").ToList

回答by IAmCodeMonkey

If you use Linq, you can use the ToList() extension method

如果使用 Linq,则可以使用 ToList() 扩展方法

Dim strings As List<string> = string_variable.Split().ToList<string>();