1

Can I add the numbers I get in a string format using the below code:

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

The output of this code is: "50.00 GiB, 16.00 GiB", for example.

I decided to first remove the units from it so that I can add the numbers straight away. Therefore, I changed the code to:

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

Now, the output is: "50.00, 16.00"

How do I add these numbers which are in a string using LINQ, to get "66.00" as the output?

3
  • Since it is a string, you could try .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToSingle(n.Trim())).Sum(); You could probably re-work that to avoid the string.Join at the beginning. Commented Apr 12, 2018 at 4:20
  • Hey @RonBeyer.. it is IEnumerable<string>.. I tried to do the below but I do not get nay output on Postman... ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToSingle(n.Trim())).Sum() Commented Apr 12, 2018 at 4:24
  • Then use .First() at the beginning of that, ie: .First().Split(...)... Don't use .ToString before it. Commented Apr 12, 2018 at 4:25

1 Answer 1

2

Change the statement to:

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,

For clarity on the LINQ pipeline:

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

3 Comments

I'd upvote this if you put the entire thing in there, and got rid of the string.Join at the beginning.
@RonBeyer.. I am using string.join because Size being used in the select statement is a IEnumerable<string>: Select(b => b.Size).. So, not using string.Join() gives me an error.
The LINQ statements form a pipeline, so what started as IEnumerable<string> gets converted to IEnumberable<decimal> by the last Select the a single decimal by the Sum. You could convert it back to a string by adding ToString() after the Sum

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.