tags:

views:

73

answers:

4

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

+2  A: 

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.

Annath
I agree - simple and easy to read too.There's an old saying... "if you have a problem and you think you need to solve it with a regular expression... you now have two problems"
Tejs
+5  A: 

Like this:

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

Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));
SLaks
missing a parentheses after the first Parse, thats what you get for typing it in without checking in VS.
Yuriy Faktorovich
+1  A: 

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.

Tim Hoolihan
It's a 1-liner if you jam everything onto one line, sure...
Aaronaught
fair enough, but if you get linq, that's not actually a bad one liner. and i should have said single statement, not 1 liner, i'd format as 3 lines like above.
Tim Hoolihan
+5  A: 

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

Paul Kohler
(unless you are after the other point!)
Paul Kohler
Well, now, that's just *too* easy! :)
NateD