Split string, convert ToList() in one line

后端 未结 10 1893
借酒劲吻你
借酒劲吻你 2020-11-27 10:00

I have a string that has numbers

string sNumbers = \"1,2,3,4,5\";

I can split it then convert it to List

         


        
10条回答
  •  春和景丽
    2020-11-27 10:51

    My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).

    string sNumbers = "1,2,hh,3,4,x,5";
    

    Trying to follow Pcode Xonos Extension Method:

    public static List SplitToIntList(this string list, char separator = ',')
    {
          int result = 0;
          return (from s in list.Split(',')
                  let isint = int.TryParse(s, out result)
                  let val = result
                  where isint
                  select val).ToList(); 
    }
    

提交回复
热议问题