0

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
}
1
  • 2
    What should happen when the string cannot be successfully converted? A loop of some kind is needed, but LINQ generally makes this an easy task. The posted code is also a bit .. confusing. Commented Mar 20, 2016 at 6:05

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.