展示C#中列表中的重复项

3

我正在开发一个 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 it new {g.Key g.Count()} - xdtTransform
.Select(g => new {key = g.Key, count = g.Count()}).ToList(); - jdweng
3个回答

5

duplicates中存储实际的分组,而不是键:

var duplicates = answerData
            .GroupBy(i => i)
            .Where(g => g.Count() > 1);

然后您可以通过这些组进行迭代:

foreach (var d in duplicates)
{           
    MessageBox.Show(d.Key + " " + d.Count().ToString());
}

这个示例对每个组进行了两次计数,即迭代。或者,您可以像@HimBromBeere建议的那样存储同时包含KeyCount的对象。


4
你只需要在你的Select中返回数字即可:
var duplicates = answerData
            .GroupBy(i => i)
            .Select(g => new { Key = g.Key, Count = x.Count() })
            .Where(x => x.Count > 1);

请注意,我改变了您的语句顺序,以避免重复执行 g.Count()

0
你可以像这样做 出于性能考虑,你需要使用字典。
            List<String> answerData = new List<String>();

        Dictionary<string,int> map = new Dictionary<string, int>();
        foreach (var data in answerData)
        {
            if (map.ContainsKey(data))
            {
                map[data]++;
            }
            else
            {
                map.Add(data, 1);
            }
        }

        foreach (var item in map)
        {
            if (item.Value > 1)
            {
                Console.WriteLine("{0} - {1}", item.Key, item.Value);

            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接