Different111222
Different111222

Reputation: 1535

How to convert a c# comma separated values string into a list?

I'm using C# ASP.NET 4 and SQL Server 2008 R2

I'm getting an object scalar from sql server which is a string containing comma separated values of the form:

7, 12, ... 1, 65

I would like to convert this object into a list?

I thought of the direction:

List<int> myList = new List<int>(new int[] (List)mySqlClass.mySqlQueryReturningAnObject("SELECT CLAUSE");

but this is not going to work.

How do I convert this object into a list?


Full answer:

This answer in use is according to the selected answer (before the update)

List<int> myList = new List<int>(mySqlClass.mySqlQueryReturningAnObject("SELECT CLAUSE").ToString().Split(',').Select(x => Convert.ToInt32(x)).ToList());

Upvotes: 1

Views: 7426

Answers (6)

Marcello Faga
Marcello Faga

Reputation: 1204

        private void TestParse()
        {
            string commaseparatedstring = "3, 5,6,19";

            int parsedvalue = 0;

            List<int> valuesint =
                commaseparatedstring.Split(',').Select(elem => int.TryParse(elem, out parsedvalue) ? parsedvalue : 0).ToList(); 

        }

Upvotes: 2

Ribtoks
Ribtoks

Reputation: 6922

var intValues = line.Split(',').Select(x => Convert.ToInt32(x)).ToList();

Update

To ensure your code would be able to process strings like 1,2,3,,,4,5,6 you can use overload of String.Split method

var intValues = line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => Convert.ToInt32(x))
                    .ToList();

Upvotes: 17

Tigran
Tigran

Reputation: 62265

You can use simple Array.ConvertAll instuction, like this:

string str = "1,2,3,4,5,7,8,9";
int[]resultInArray = Array.ConvertAll( str.Split(','), item => int.Parse(item));

Upvotes: 2

Gaz Winter
Gaz Winter

Reputation: 2989

You could try assigning the result to a variable.

Then convert it into a string (if its not already one)

Then do a string split on the comma and assigning the results to a list.

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131749

Did you try String.Split?

You can split your string with a line as simple as this:

var myString="1,2,4,5,6";
var numberList=myString.Split(',');

Upvotes: 2

dodexahedron
dodexahedron

Reputation: 4657

Use the .Split() method on the string. It will return an array of strings.

string yourResult = "1,2,3,4,5";
string[] resultsArray = yourResult.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 5

Related Questions