开发者

How to convert a string into a Point?

开发者 https://www.devze.com 2022-12-28 11:58 出处:网络
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# to turn \"14,

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# to turn "14,42" into new Point(14,42);?

I know the Regex for doing that is /(\d+),(\d+)/, but I'm having a hard time turning those two match groups into ints in C#.


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


Like this:

string[] coords = str.Split(',');

Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消