skip to Main Content

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


  1. You can try something like this

    using System;
    using System.Collections.Generic;

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Hello World");
            var stringList = new List<string> {
                "Sandwich - 5.00 ",
                "no onions",
                "bbq sauce - 1.00",
                "Can - 1.00",
                "coke"
            };
        
            decimal total = 0.00m;
            foreach( var s in stringList )
            {
                decimal numericValue = 0.00m;
                var dashLocation = s.IndexOf('-');
                if (dashLocation > -1)
                {
                    var stringValue = s.Substring(dashLocation+1);
                    if (Decimal.TryParse(stringValue, out numericValue))
                    {
                        total += numericValue;
                    }
                }
            }   
            Console.WriteLine("Total {0}", total ); 
        }
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search