string tags = \"9,3,12,43,2\"
List TagIds = tags.Split(\',\');
This doesn\'t work cause the split method returns a string[]
You can use LINQ w/ int.Parse()
to convert the string[]
to an IEnumerable<int>
and then pass that result to the List<T>
constructor:
var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));
Without LINQ Query , you can choose this method ,
string tags = "9,3,12,43,2";
List<string> numbers = nos.Split(',').ToList<string>();
and then you can convert this List into integer type...
I stumbled upon this and I just want to share my own solution without linq. This is a primitive approach. Non-integer values will not be added in the list also.
List<int> TagIds = new List<int>();
string[] split = tags.Split(',');
foreach (string item in split)
{
int val = 0;
if (int.TryParse(item, out val) == true)
{
TagIds.Add(val);
}
}
Hope this helps.
string tags = "9,3,12,43,2"
List<int> TagIds = tags.Split(',').Select(x => x.Trim()).Select(x=> Int32.Parse(x)).ToList();
A little LINQ goes a long way:
List<int> TagIds = tags.Split(',')
.Select(t => int.Parse(t))
.ToList();
If you are using C# 3.5 you can use Linq to achieve this
string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(s=>int.Parse(s)).ToList();
or the short one
string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(int.Parse).ToList();