使用LINQ添加字符串的数字部分

时间:2018-04-12 04:16:11

标签: c# linq

我可以使用以下代码添加我以字符串格式获得的数字:

Size = a.Type == "Machines" ?string.Join(",", a.Info.DiskInfo.Select(b => b.Size)) : null,

此代码的输出为:"50.00 GiB, 16.00 GiB",例如。

我决定先从中移除单位,以便我可以立即添加数字。因此,我将代码更改为:

Size = a.Type == "Machines" ? string.Join(",", a.Info.DiskInfo.Select(b => b.Size).Select(c => Regex.Replace(c, "[^0-9.]", ""))) : null,

现在,输出为:" 50.00,16.00"

如何使用LINQ添加字符串中的这些数字,以获得" 66.00"作为输出?

1 个答案:

答案 0 :(得分:2)

将声明更改为:

Size = a.Type == "Machines" 
  ? a.Info.DiskInfo
     .Select(b => b.Size)
     .Select(c => Regex.Replace(c, "[^0-9.]", "")))
     .Where(x => !string.IsNullOrWhiteSpace(x))
     .Select(x => Convert.ToDecimal(x.Trim()))
     .Sum()
  : null,

为了清楚LINQ管道:

Size = a.Type == "Machines"  
  ? a.Info.DiskInfo // object
     .Select(b => b.Size) // IEnumerable<string>
     .Select(c => Regex.Replace(c, "[^0-9.]", ""))) // IEnumerable<string>
     .Where(x => !string.IsNullOrWhiteSpace(x)) // IEnumerable<string>
     .Select(x => Convert.ToDecimal(x.Trim())) // IEnumerable<decimal>
     .Sum() // single decimal
     .ToString() // single string
  : null,