首页 > 解决方案 > 在 MessageBox 中显示结果

问题描述

有 3 个最常出现的单词的代码

string words = "One one Two two three four".ToLower();

var results = words
  .Split(' ')
  .Where(x => x.Length > 3)
  .GroupBy(x => x)
  .Select(x => new { 
     Count = x.Count(), 
     Word = x.Key })
  .OrderByDescending(x => x.Count)
  .Take(3);

foreach (var item in results)
{
    MessageBox.Show(String.Format("{0} occurred {1} times", item.Word, item.Count));
}

它可以工作,但我想按一次按钮并在 MessageBox 中显示所有结果,如下所示:

在此处输入图像描述

标签: c#string

解决方案


加入字符串,然后只显示一次消息框:

MessageBox.Show(String.Join("\n", results.Select(x => String.Format("{0} occurred {1} times", x.Word, x.Count)));

或使用字符串插值:

MessageBox.Show(String.Join("\n", 
                   results.Select(x => $"{x.Word} occurred {x.Count} times"));

推荐阅读