If I have for example the following string:
"123;3344;4334;12"
and I want these numbers in a generic List<int>, I guess I don't know of a good way here other than to split in a loop and do a conversion then add to a List<int> through each iteration. Does anyone have other ways to go about this?
Updated. Here's what I came up with. I want to do this the old fashion way, not with LINQ because I'm trying to get better with just strings, arrays, lists and manipulating and converting in general.
public List<int> StringToList(string stringToSplit, char splitDelimiter) { List<int> list = new List<int>(); if (string.IsNullOrEmpty(stringToSplit)) return list; string[] values = stringToSplit.Split(splitDelimiter); if (values.Length <= 1) return list; foreach (string s in values) { int i; if (Int32.TryParse(s, out i)) list.Add(i); } return list; } This is a new string utility method I plan on using whenever I need to convert a delimited string list to List
So I'm returning an empty list back to the caller if something fails. Good/Bad? is it pretty common to do this?
Yes, there are more "elegant" ways to do this with LINQ but I want to do it manually..the old way for now just for my own understanding.
Also, what bothers me about this:
list.AddRange(str.Split(';').Select(Int32.Parse)); is that I have no idea:
- How to shove in a TryParse there instead.
- What if the
str.Split(';').Select(Int32.Parse)just fails for whatever reason...then the method that this AddRange resides in is going to blow up and unless I add a try/catch around this whole thing, I'm screwed if I don't handle it properly.