Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find all numbers in a string in a listbox and add them up

I have a listbox in winforms and it will contain a bunch of text and I want to find all the decminal numbers and add them up. All the decimal numbers will be after a hyphen. I will create an example of the listbox below.


Listbox

Sandwich - 5.00 
no onions

bbq sauce - 1.00

Can - 1.00
coke

var sum = OrderListBox.Items
        .OfType<string>()
        .Select(s => Convert.ToDecimal(s.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[1]))
        .Sum();

I have this code but it errors whenever the listbox has a blank line or a line of text without a hyphen followed by a number

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use Regex ( using System.Text.RegularExpressions; ) with the following:

string firstPattern = "-\\s*[0-9.]+";
string detailPattern = "[0-9.]+";
Regex firstRegex = new Regex(firstPattern);
Regex detailRegex = new Regex(detailPattern);
double sum = 0;
foreach (string item in listBox1.Items)
{
     string match = firstRegex.Match(item).Value;
     if (match != String.Empty)
     {
          double toAdd = 0;
          string num = detailRegex.Match(match).Value;
          Double.TryParse(num, out toAdd);
          sum += toAdd;
     }
}

This finds the strings with the hyphen followed by a number and then within that string just finds the number part of it. Then parse it to a double and add it to your sum variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading