Reputation: 1535
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?
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
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
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
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
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
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
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