我正在开发一个 WPF 应用程序,在某个时刻,我需要从字符串列表中获取/显示所有重复的字符串。(包含重复的字符串名称和该字符串在列表中出现的次数)例如:
“该列表中包含字符串'Hello' 3 次。”
到目前为止,我已经成功地获取了字符串的名称,但我无法正确获取它在列表中出现的次数。
以下是我的代码:
List<String> answerData = new List<String>();
using (MySqlCommand command = new MySqlCommand(query2, conn))
{
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
answerData.Add(reader.GetString(0));
}
}
}
var duplicates = answerData
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
foreach (var d in duplicates)
{
MessageBox.Show(""+ d + duplicates.Count().ToString()); //Here I tried to get the number
//with Count() but it doesn't work as I thought it would.
}
我应该添加/更改什么来得到我想要的结果? 编辑 如建议所示,将我的代码更改为以下内容:
var duplicates = answerData
.GroupBy(i => i)
.Where(g => g.Count() > 1);
foreach (var d in duplicates)
{
MessageBox.Show(d.Key + " " + d.Count().ToString());
}
现在它运行得非常流畅。 感谢大家!
Select
。 - Franck.Select(g => g.Key)
You have selected only the key. If you want the count you should get itnew {g.Key g.Count()}
- xdtTransform