Seb Dammer
Seb Dammer

Reputation: 55

Get value of a listBox item after specific character

I've got a difficult question:

I have a ListBox with some items in it. Every item has a structure like this: string, double, double.

in code:

listBox.Items.Add(name2.Text + " " + 
                  Annuitätenrechner.zmErg.ToString("0.00") + "€" + " " +
                  Annuitätenrechner.zgErg.ToString("0.00") + "€");

I'd like to compare the last double (zgErg) of an item with the last double of the other items, and afterwards get the smallest value of all items.

Already wrote something how it could be like:

private void bCompare_Click(object sender, RoutedEventArgs e)
{
   // string ext = str.Substring(0, str.LastIndexOf("#") + 1);

    var numbers = listBox.Items.Cast<object>().Select(obj => Convert.ToInt32(obj));

    foreach (int obj in numbers)
    {

    }

    int min = numbers.Min();
} 

Upvotes: 1

Views: 313

Answers (1)

Steve
Steve

Reputation: 216290

If the the name2 textbox doesn't contain spaces then you could reach your list of decimal values using a single line

var numbers = listBox.Items
                     .Cast<string>()
                     .Select(obj => decimal.Parse(obj.Split(' ')[2],
                                    NumberStyles.Currency, CultureInfo.CurrentCulture));

of course getting the Min value is just another little step

decimal minValue = listBox.Items
                      .Cast<string>()
                      .Select(obj => decimal.Parse(obj.Split(' ')[2], 
                                     NumberStyles.Currency, CultureInfo.CurrentCulture))
                      .Min();

Notice that you have formatted your listbox items with the decimal part so I think it is correct to extract the value using decimal types methods.

In case your name2 textbox contains spaces then the code should not use directly the second item returned by the Split method but use the Last method on the array returned by the Split

var numbers = listBox.Items
                     .Cast<string>()
                     .Select(obj => decimal.Parse(obj.Split(' ')
                     .Last(),NumberStyles.Currency, CultureInfo.CurrentCulture));

Upvotes: 1

Related Questions