Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load a comma separated numbers to List<int> in c#

Tags:

c#

string formIdList = "8256, 8258, 8362, 8120, 8270, 8271, 8272, 8273, 8257, 8279, 8212, 8213, 8214, 8215, 8216, 8217, 8218, 8219, 8231, 8232, 8233, 8234, 8235, 8242, 8248, 8251, 8252, 8254, 8255, 8262, 8263, 8264, 8265, 8266, 8290, 8292, 8293, 8294, 8300, 8320, 8230, 8227, 8226, 8225, 8224, 8223, 8222, 8221, 8291, 8261, 8241, 8228, 8220, 8211, 8208, 8207, 8206, 8205, 8204, 8203, 8202, 8201, 8153, 8151, 8150, 8130, 8122, 8000, 8101, 8102, 8103";

var temp = formIdList.Split(',');

List<int> ids = new List<int>();

I need to load the temp into ids. I can use a for-loop but I'm sure there is a better way.

like image 407
GaneshT Avatar asked Jan 10 '12 19:01

GaneshT


People also ask

How do you store comma-separated values in an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How can I convert comma-separated string into a list string C#?

To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.


2 Answers

You could use LINQ:

string formIdList = ...
List<int> ids = formIdList.Split(',').Select(int.Parse).ToList();
like image 135
Darin Dimitrov Avatar answered Sep 30 '22 00:09

Darin Dimitrov


List<int> ids = formIdList.Split(',').Select(i=>int.Parse(i)).ToList();
like image 44
ek_ny Avatar answered Sep 29 '22 23:09

ek_ny