I had this code:
String[] lineElements;
. . .
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
lineElements = line.Split(',');
. . .
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(',');
. . .
...gives me, "Cannot implicitly convert type 'string[]' to 'System.Collections.Generic.List'"
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
string.Split()
returns an array - you can convert it to a list using ToList()
:
listStrLineElements = line.Split(',').ToList();
Note that you need to import System.Linq
to access the .ToList()
function.
Either use:
List<string> list = new List<string>(array);
or from LINQ:
List<string> list = array.ToList();
Or change your code to not rely on the specific implementation:
IList<string> list = array; // string[] implements IList<string>
Include using namespace System.Linq
List<string> stringList = line.Split(',').ToList();
you can make use of it with ease for iterating through each item.
foreach(string str in stringList)
{
}
String.Split()
returns an array, hence convert it to a list using ToList()
Just u can use with using System.Linq;
List<string> stringList = line.Split(',') // this is array
.ToList(); // this is a list which you can loop in all split string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With