检查字符串在列表框中出现的次数

Check how many times a string appear in listbox

我有一个列表框,我使用以下代码从按钮加载项目:

OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
    string[] lines = System.IO.File.ReadAllLines(ofd.FileName);
    foreach (string line in lines)
    {
        listBox1.Items.Add(line);
    }
}

我加载的文件包含列表 (.txt),格式为:

username:password:proxy

我的目标是只找到代理,并统计每个代理出现的次数。

所以我使用这个代码:

List<string> proxies = new List<string>();
foreach (string s in listBox1.Items)
            {
                proxies.Add(Regex.Match(s, @"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\:\d{2,5}\b", RegexOptions.Singleline).ToString());
            }

现在我已将文件中的所有代理都列在一个列表中,但我如何才能以某种格式保存它,以便每个代理显示它出现了多少次?

例如:

proxy1 - 8 (times)
proxy2 - 5 (times)
proxy3 - 4 (times)

如果您想以提供的格式打印出报告,即

  proxy1 - 8 (times)
  proxy2 - 5 (times)
  proxy3 - 4 (times)

你可以使用 Linq

String report = String.Join(Environment.NewLine,
  File.ReadLines(@"C:\MyFile.txt")
    .Select(line => line.Split(':')[2])
    .GroupBy(item => item) 
    .Select(chunk => String.Format("{0} - {1} (times)", chunk.Key, chunk.Count())));

Console.Write(report);
// Or 
// listBox1.Text = report;

而不是

listBox1.Items.Add(line);

您想做这样的事情...

ListBox1.Items.Insert(0,new ListItem("Label", "Value"))