Advertisement
jlalt

C# - Check Items Repeat

Jun 1st, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. namespace ListBoxItems
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         public Form1()
  16.         {
  17.             InitializeComponent();
  18.             List<string> values = new List<string>();
  19.             values.Add("6");
  20.             values.Add("3");
  21.             values.Add("9");
  22.             values.Add("1");
  23.             values.Add("5");
  24.             values.Add("3");
  25.             values.Add("85");
  26.             values.Add("85");
  27.             values.Add("85");
  28.             values.Add("85");
  29.             values.Add("85");
  30.             values.Add("5");
  31.             listBox1.DataSource = values;
  32.             int which = ItemsRepeated(listBox1, 5); // check if a item repeated 5 times by order.
  33.             if (which != -(int.MaxValue))
  34.             {
  35.                 MessageBox.Show("Item Repeated: " + which.ToString());
  36.             }
  37.             else
  38.             {
  39.                 MessageBox.Show("none repeated like that!");
  40.             }
  41.         }
  42.         private int ItemsRepeated(ListBox box, int times)
  43.         {
  44.             int attempts = 0, len = box.Items.Count;
  45.             for(int i = 0; i < len; i++)
  46.             {
  47.                 if(i > 0 && int.Parse(box.Items[i].ToString()) == int.Parse(box.Items[( i - 1 )].ToString()))
  48.                 {
  49.                     attempts++;
  50.                     if(attempts == times)
  51.                     {
  52.                         return int.Parse(box.Items[i].ToString());
  53.                     }
  54.                 }
  55.                 else
  56.                 {
  57.                     attempts = 1;
  58.                     if(times <= 1)
  59.                     {
  60.                         return int.Parse(box.Items[i].ToString());
  61.                     }
  62.                 }
  63.             }
  64.             return -(int.MaxValue);
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement