如何计算列表框中的重复项并在其旁边显示重复项的数量

本文关键字:显示 何计算 列表 计算 | 更新日期: 2023-09-27 18:36:01

所以我有一个按钮,如果你单击它,它会"Candy"添加到listbox,我该怎么做,如果添加另一个同名的项目,而不是将其添加到新行中,更新第一行以显示 x2、3、4 等。这是否可能,或者我必须进行另一次Listbox并匹配索引?我已经用另一个listbox和一个 int 变量尝试了以下内容。

private void btnCandy_Click(object sender, EventArgs e)
    {
        lstProducts.Items.Add("Candy");
        foreach (var item in lstProducts.Items)
        {
            if (item.ToString() == "Candy")
            {
                ++Productcount;
                lstQuantity.Items.Add(Productcount);
                if (Productcount > 1)
                {
                    lstQuantity.Items.Insert(lstProducts.Items.IndexOf("Candy"), Productcount);
                }
            }
        }
    }

如何计算列表框中的重复项并在其旁边显示重复项的数量

using System.Text.RegularExpressions;

用:

private void btnCandy_Click(object sender, EventArgs e)
{
    string query = "Candy";
    bool isExist = false;
    for (int i = 0; i < lstProducts.Items.Count; i++)
    {
        var s = lstProducts.Items[i].ToString();
        if (s.StartsWith(query))
        {
            if (s == query)
            {
                lstProducts.Items[i] = query + "x2";
                isExist = true;
                break;
            }
            else
            {
                // Escape your plain text before use with regex
                var pattern = Regex.Escape(query);
                // Check if s has this formnat: queryx2, queryx3, queryx4, ...
                Match m = Regex.Match(s, "^" + pattern + @"x('d+)$");
                if (m.Success)
                {
                    lstProducts.Items[i] = query + "x" + (Int32.Parse(m.Groups[1].Value) + 1);
                    isExist = true;
                    break;
                }
            }
        }
    }
    if (!isExist) lstProducts.Items.Add(query);
}

注意:

  • 'd表示任何数字 (0 - 9)

我会尝试遍历列表框项目,如果我找到"糖果",则获取该索引并更新标题。

private void btnCandy_Click(object sender, EventArgs e)
{
    bool found = false;
    foreach (var item in lstProducts.Items)
    {
        if (item.ToString().StartsWith("Candy"))
        {
            // update item title
            found = true;
            break; // no need to continue
        }
    }
    if(!found)
    {
        lstProducts.Items.Add("Candy");
    }
}

这样您就不会添加重复项

这里有一些伪代码可以帮助你。将此添加到按钮单击事件中:

int i = 0;
foreach (string item in listbox1.Items)
{
     If (item == textbox1.text) //textbox1.text contains the string such as 'candy'
    {
         i++;
         listbox1.Items.Remove(item);
         listbox1.Items.Add(textbox1.text + " " + i.ToString());
    }
}

您可能需要根据需要重置计数器。