【问题标题】:How to distinct and count the duplicates inside a listbox?如何区分和计算列表框中的重复项?
【发布时间】:2019-03-27 19:33:14
【问题描述】:

我正在尝试创建一个列表框,我可以使用 datagridview 在其中添加项目,问题是我想确定哪个项目是重复的以及它重复了多少次。

  • 项目1
  • 项目1
  • 项目2
  • 项目2
  • 项目2

输出 item1=2, item2=3


这是我尝试过的一个,它显示了最后一个重复的项目

int count = 0;

 for (int i = 0; i < listBox1.Items.Count; i++)
 {
  var s = listBox1.Items[i].ToString();
  if (s.StartsWith(listfood))
   {
    if (s == listfood)
     {
      ++count;
     }             
   }
 }
MessageBox.Show(count.ToString());

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试

    var duplicateItems = listBox1.Items.GroupBy(x => x.ToString())
                .Where(x => x.Count() > 1)
                .Select(x => new { Value = x.Key, Count = x.Count() })
                .ToList();
    

    【讨论】:

    • 废话,你打败了我 2 分钟。我正在测试我的。赞成:)
    【解决方案2】:
    using System.Linq;
    
    // ...
    
    var duplicates = listBox1.Items.GroupBy(x => x)
                                   .Where(g => g.Count() > 1)
                                   .Select(y => new { ItemName = y.Key, Occurrences = y.Count() })
                                   .ToList();
    
    foreach (var duplicate in duplicates)
        MessageBox.Show($"{duplicate.ItemName}: {duplicate.Occurrences}");
    

    此解决方案使用LINQ 查询listBox1Items 集合并过滤掉我们不关心的任何数据。

    首先,我们使用GroupBy 对项目进行排序。然后,Where 将过滤掉集合中仅存在一次的所有项目。 Select 允许我们将过滤后集合中剩余的项目“投影”到“新形式”中(我们使用带有 ItemNameOccurrences 属性的 anonymous type 来跟踪重复项的名称和数量出现在集合中的次数)。

    最后,ToList 将集合从 IEnumerable&lt;string&gt; to aListtype.ToListis optional depending on how you plan on usingduplicates. In fact, my example doesn't need to callToListbecause aforeachloop can iterate over anIEnumerable` 集合转换。

    【讨论】:

    • 我不明白如何完成这项工作我对 c# 还是很陌生,我正在使用它在 Visual Studio 的表单上输出。你能解释一下你的代码是如何工作的吗?
    • @krljde 抱歉,我很快就写好了,并让它将输出写入控制台。我编辑了我的答案,所以现在它会像你原来的例子一样做一个消息框。我还会添加一个简短的解释。
    【解决方案3】:

    我知道上面的答案肯定会起作用,但我无法理解并使它起作用。这对我有用,我将列表框的值传输到一个数组并检查该数组中的重复项。

         var list = new List<string>();
                foreach(var item in listBox1.Items)
                {
                    list.Add(item.ToString());
                }
                var r = from b in list
                        group b by b into g
                        let count = g.Count()
                        orderby count descending
                        select new { Value = g.Key, Count = count };
                foreach(var x in q)
                {
                    MessageBox.Show("value: " + b.Value + " Count:" + b.Count);
                }
    

    Found my answer here

    【讨论】:

    • Linq Query Expressions 用于此答案,而 Linq Fluent Expressions 用于其他答案。 Ref。您仍然可以通过简单地将代码更改为 var r = from b in listBox1.Items.Select(x => x.ToString()) 来避免使用 list 变量和 for 循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2019-08-17
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多