使用TryParse C#将list <string>转换为list <decimal>

时间:2016-03-20 06:03:46

标签: c#

如果可能,我们如何使用返回类型为decimal.TryParse的{​​{1}}将字符串列表转换为十进制列表,以便我可以执行此类操作

bool

2 个答案:

答案 0 :(得分:4)

假设我只选择成功转换的值:

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

答案 1 :(得分:1)

您可以通过

轻松将list<string>转换为数组listItem[]
listItem[] strArr = yourList.ToArray();

现在,定义一些decimal array并尝试使用TryParse转换为

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