Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

c# - How to Convert Persian Digits in variable to English Digits Using Culture?

I want to change persian numbers which are saved in variable like this :

string Value="???????"; 

to

string Value="1036751";

How can I use easy way like culture info to do this please?

my sample code is:

List<string> NERKHCOlist = new List<string>();
NERKHCOlist = ScrappingFunction(NERKHCO, NERKHCOlist);
int NERKHCO_Price = int.Parse(NERKHCOlist[0]);//NERKHCOlist[0]=??????? 

<= So it can not Parsed it to int
And This is in my function which retun a list with persian digits inside list items

protected List<string> ScrappingFunction(string SiteAddress, List<string> NodesList)
{    
    string Price = "null";
    List<string> Targets = new List<string>();
    foreach (var path in NodesList)
    {
        HtmlNode node = document.DocumentNode.SelectSingleNode(path.ToString());//recognizing Target Node
        Price = node.InnerHtml;//put text of target node in variable(PERSIAN DIGITS)
        Targets.Add(Price);
    }
    return Targets;
}
question from:https://stackoverflow.com/questions/18340808/how-to-convert-persian-digits-in-variable-to-english-digits-using-culture

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest two approaches to handle this issue(I Create an extension method for each of them):

1.foreach and replace

public static class MyExtensions
{
     public static string PersianToEnglish(this string persianStr)
     {
            Dictionary<char, char> LettersDictionary = new Dictionary<char, char>
            {
                ['?'] = '0',['?'] = '1',['?'] = '2',['?'] = '3',['?'] = '4',['?'] = '5',['?'] = '6',['?'] = '7',['?'] = '8',['?'] = '9'
            };
            foreach (var item in persianStr)
            {
                persianStr = persianStr.Replace(item, LettersDictionary[item]);
            }
            return persianStr;
     }
}

2.Dictionary.Aggregate

public static class MyExtensions
{
      public static string PersianToEnglish(this string persianStr)
      {
            Dictionary<string, string> LettersDictionary = new Dictionary<string, string>
            {
                ["?"] = "0",["?"] = "1",["?"] = "2",["?"] = "3",["?"] = "4",["?"] = "5",["?"] = "6",["?"] = "7",["?"] = "8",["?"] = "9"
            };
            return LettersDictionary.Aggregate(persianStr, (current, item) =>
                         current.Replace(item.Key, item.Value));
      }
}

More info about Dictionary.Aggregate: Microsoft

Usage:

string result = "???????".PersianToEnglish();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...