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
2
Answers
You can try something like this
using System;
using System.Collections.Generic;
You could use Regex (
using System.Text.RegularExpressions;
) with the following: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.