Last post Mar 27, 2019 02:14 AM by Ackerly Xu

• inkaln

Member

95 Points

413 Posts

using Int.TryParse on strings that have characters, integers and decimals/doubles

Hi....not sure what the best approach is for this.

I have a var list that contains a list of key, value where key could be any string such as "abc", "25", "35.26", "29.7"

I want to use Int.TryParse to parse these to integers where the first one would return false.  The "25" converts fine but the last two won't as I would need to use decimal.TryParse....but I have a huge list of these and each value is attached to a key that has an integer value associated with them...i.e. "abc" could have 25 records so value would be 25 and so forth.

How do I write a method that converts to integers, given that alphabetic or alphanumeric characters would fail, but decimal would return the rounded number to the nearest whole.   So "35.26" would return 35 and "29.7" would return 30 and so on...?  And once I have the list, I'd like to create a key, value paired list where it groups each integer in how many times it occurs in the list.

• Ackerly Xu

Contributor

3480 Points

1300 Posts

Re: using Int.TryParse on strings that have characters, integers and decimals/doubles

Mar 27, 2019 02:14 AM|Ackerly Xu|LINK

Hi inkaln,

Not sure about your requirement, if you want to parse value which may be integer , decimal and character, you could use decimal.TryParse and then use Math.Round to get rounded number.

If you want to group the key value  pair, you could use group by.

Below is my code.

```  protected void Page_Load(object sender, EventArgs e)
{

List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
list =  list.Select(  //select method will map your data , it will input the every key value pair and output the returned value
kv =>{
decimal dec;
if (decimal.TryParse(kv.Key, out dec)) // try parse the key
{
// use Math.Round to get the integer of the key
return new KeyValuePair<string, string>(Math.Round(dec).ToString(), kv.Value);

}
// if couldn't parse the key, return original keyvalue pair
return kv;
}).ToList();
var query =  list.GroupBy(kv => kv.Key); // group the dada according the the key
foreach (IGrouping<string,KeyValuePair<string,string>> group in query) // loop through every group
{
Response.Write("<br/>");
Response.Write(group.Key + " 's count " + group.Count() ); // get the key of group, it will be 26,24,abc, you could get the count of elements in the group throught group.Count()
Response.Write("<br/>");
Response.Write("<br/>");
foreach (KeyValuePair<string,string> item in group)
{

Response.Write(item.Key + ":" + item.Value + "<br/>"); // output every element in the group
}
}

}```

The result.