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
}
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
}
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();
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
}