How to convert a string into a Point?

后端 未结 4 1129
执笔经年
执笔经年 2020-12-21 02:43

I have a list of strings of the format \"x,y\". I would like to make them all into Points. The best Point constructor I can find takes two ints. What is the best way in C# t

相关标签:
4条回答
  • 2020-12-21 03:05

    Like this:

    string[] coords = str.Split(',');
    
    Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));
    
    0 讨论(0)
  • 2020-12-21 03:08

    You could use a simple string split using ',' as the delimiter, and then just use int.parse(string) to convert that to an int, and pass the ints into the Point constructor.

    0 讨论(0)
  • 2020-12-21 03:09

    There is Point.Parse (System.Windows.Point.Parse, WindowsBase.dll) and then you don't need to mess around with regex or string splitting etc.

    http://msdn.microsoft.com/en-us/library/system.windows.point.parse.aspx

    PK :-)

    0 讨论(0)
  • 2020-12-21 03:21

    Using Linq this could be a 1-liner

    //assuming a list of strings like this
    var strings = new List<String>{
       "13,2",
       "2,4"};
    
    //get a list of points
    var points = (from s in strings
                 select new Point(s.split(",")[0], s.split(",")[1]))
                 .ToList();
    
     // or Point.Parse as PK pointed out
    var points = (from s in strings select Point.Parse(s)).ToList();
    

    I'm using a mac to write this, so I can't check syntax, but that should be close.

    0 讨论(0)
提交回复
热议问题