从ListBox项

时间:2016-07-04 10:30:27

标签: c# wpf listbox substring

我有一个包含X项的ListBox。 Item是像String,double,double一样构建的。我希望第二个double的smalles值的项目与Label中的字符串一起显示。

示例项目:名称值1值2 所以每个部分都被空格分开。该代码仅用于获取第二个double的最小值,但不取该项的字符串。

vName的功能不起作用。

    private void bVergleich_Click(object sender, RoutedEventArgs e)
    {
        if (listBox.Items.Count <= 0)
        {
            MessageBox.Show("Bitte erst Einträge hinzufügen.");
        }
        else
        {
            int anzahl = listBox.Items.Count;
            string str = listBox.Items[anzahl].ToString();
            string vName = str.Substring(0, str.IndexOf(" ") + 1);

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

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

            lVergleich.Content = vName + " " + minValue + "€";
        }
    }

我是如何获得字符串的?

2 个答案:

答案 0 :(得分:1)

我将尝试使用您的代码示例。您可以使用旧学校的方法,并通过所有条目的for循环运行。

private void bVergleich_Click(object sender, RoutedEventArgs e)
{
    if (listBox.Items.Count <= 0)
    {
        MessageBox.Show("Bitte erst Einträge hinzufügen.");
    }
    else
    {
        List<decimal> tmpListe = new List<decimal>();
        int anzahl = listBox.Items.Count;

        for (int i = 0; i < anzahl; i++)
        {
            string str = listBox.Items[i].ToString();
            // collect all the second double values
            tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture));
        }

        // get the minimal value and its index
        decimal minValue = tmpListe.Min();
        int index = tmpListe.IndexOf(tmpListe.Min());

        // use the index to get the name
        string str2 = listBox.Items[index].ToString();
        string vName = str2.Substring(0, str2.IndexOf(" ") + 1);

        // write down your comparison
        lVergleich.Content = vName + " " + minValue + "€";
    }
}

这会显示列表中第一个最低值。

我个人也建议使用具有3个属性和重写ToString方法的自定义类进行显示。然后收集通用List中的所有项目,并将此列表绑定到ListBox

答案 1 :(得分:0)

您可以按所需的值对集合进行排序,并按顺序获取第一个元素

List<string> list = listBox.Items.ToList();

list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1])));

string x = list.First();

或者只是

string result = listBox.Items.OrderBy(y =>  decimal.Parse(y.Split(' ')[1])).First();