frenchie
frenchie

Reputation: 52017

formatting phone number with linq

I'm storing my phone numbers in the database as strings of digits; for instance 4081234567. I'm looking to format this string of digits in the US phone format XXX-XXX-XXXX. This is what I have and it's not working:

ThePhone = "4081234567";
char[] ThePhoneString = ThePhone.ToArray();
var ThePhoneFormat = ThePhoneString.Take(3).ToList().ToString() + "-" +ThePhoneString.Skip(3).Take(3).ToString + "-" + ThePhoneString.Skip(6).Take(4).ToString();

I'm sure there's a better way to do it; what do you suggest?

Thanks..

Upvotes: 0

Views: 1259

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134571

You don't need LINQ for this. This sort of manipulation is not what LINQ is used for.

Use a regular expression or something else instead.

var phoneNumber = "4081234567";
var phoneFormat = Regex.Replace(phoneNumber, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");

Upvotes: 4

iamkrillin
iamkrillin

Reputation: 6876

String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

This question was also asked here Fastest way to format a phone number in C#?

Upvotes: 0

Related Questions