Split out ints from string

前端 未结 13 1366
情歌与酒
情歌与酒 2021-01-17 17:45

Let\'s say I have a web page that currently accepts a single ID value via a url parameter:
http://example.com/mypage.aspx?ID=1234

I want to change it to acce

13条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 18:28

    Something like this might work:

    public static IList GetIdListFromString(string idList)
    {
        string[] values = idList.Split(',');
    
        List ids = new List(values.Length);
    
        foreach (string s in values)
        {
            int i;
    
            if (int.TryParse(s, out i))
            {
                ids.Add(i);
            }
        }
    
        return ids;
    }
    

    Which would then be used:

    string intString = "1234,4321,6789";
    
    IList list = GetIdListFromString(intString);
    
    foreach (int i in list)
    {
        Console.WriteLine(i);
    }
    

提交回复
热议问题