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

4 Answers 4

13

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

3
  • Well, now, that's just too easy! :)
    – NateD
    Commented Apr 27, 2010 at 3:14
  • I added System.Windows to reference and get error(no point.parse). Where can I find WindowsBase.dll? I am using vs2017 in VB in a windows form. Commented Feb 14, 2020 at 19:12
  • Do note the post is about 10 years old now! I would start with looking at the docs for whatever version and stack you are working with. Commented Feb 14, 2020 at 23:06
12

Like this:

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

Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));
1
  • 3
    missing a parentheses after the first Parse, thats what you get for typing it in without checking in VS. Commented Apr 27, 2010 at 2:35
2

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.

1
  • 2
    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
    Commented Apr 27, 2010 at 2:33
1

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.

1
  • 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. Commented Apr 27, 2010 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.