Sometimes you need to separate a string and convert it to an array or list of the specified type. For example, if the server receives the submitted checkbox value, it may be an ID string, similar: 56,657, and 8, you need to convert it into an int array or list <t> for subsequent processing.
After converting a string to list <t>, we can see the discussion about this.
We can use the array. convertall generic method to implement it. The Code is as follows:
string str = "56,657,0,1,2,3,4,5,6,7,8";int[] arrInt = Array.ConvertAll<string, int>(str.Split(','), s => int.Parse(s));foreach (int i in arrInt) Console.WriteLine(i);
Or, we want to use some "tricks and tricks", such as the string extension method:
public static List<T> ToList<T>(this string str, char split, Converter<string, T> convertHandler){ if (string.IsNullOrEmpty(str)) { return new List<T>(); } else { string[] arr = str.Split(split); T[] Tarr = Array.ConvertAll(arr, convertHandler); return new List<T>(Tarr); }}
Call method:
List<int> intList = str.ToList<int>(',', s => int.Parse(s));