How can I convert comma separated string into a List

前端 未结 11 2145
我寻月下人不归
我寻月下人不归 2020-12-07 09:16
string tags = \"9,3,12,43,2\"

List TagIds = tags.Split(\',\');

This doesn\'t work cause the split method returns a string[]

相关标签:
11条回答
  • 2020-12-07 09:42

    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)));
    
    0 讨论(0)
  • 2020-12-07 09:46

    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...

    0 讨论(0)
  • 2020-12-07 09:46

    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.

    0 讨论(0)
  • 2020-12-07 09:49
    string tags = "9,3,12,43,2"
    
    List<int> TagIds = tags.Split(',').Select(x => x.Trim()).Select(x=> Int32.Parse(x)).ToList();
    
    0 讨论(0)
  • 2020-12-07 09:53

    A little LINQ goes a long way:

     List<int> TagIds = tags.Split(',')
             .Select(t => int.Parse(t))
             .ToList();
    
    0 讨论(0)
  • 2020-12-07 09:56

    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();
    
    0 讨论(0)
提交回复
热议问题