Babu
Babu

Reputation: 29

convert list<string> to list<decimal> using TryParse C#

If possible, How can we convert List of string to list of decimal using decimal.TryParse whose return type is bool so that I can do something like this

if(true)
{
//to do
} 
else
{
// to do
}

Upvotes: 0

Views: 1730

Answers (2)

Raj Baral
Raj Baral

Reputation: 671

You can easily convert your list<string> to array listItem[] by

listItem[] strArr = yourList.ToArray();

Now, define some decimal array and try to convert them using TryParse as

decimal n;
decimal[] decArr;
if(strArr.All(x => Decimal.TryParse(x, out n)))
{
 decArr = Array.ConvertAll<string,decimal>(strArr, Convert.ToDecimal);
}
else
{
//to do
}

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29846

Assuming that I'm selecting only the values that converted successfully:

List<string> lstStr = GetListString(); // Get it somehow

List<decimal> decs = lstStr.Select(str =>
{
   decimal item = 0m;
   return new 
   {
     IsParsed =  decimal.TryParse(str, out item),
     Value = item
   };
}).Where(o => o.IsParsed).Select(o => o.Value).ToList();

Upvotes: 4

Related Questions