[C # tips for collection] converting strings to list

Source: Internet
Author: User

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));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.