How to distinct and count the duplicates inside a listbox?Fluent and Query Expression — Is there any benefit(s) of one over other?How to Count Duplicates in List with LINQHow do I calculate someone's age in C#?How do I enumerate an enum in C#?Should 'using' directives be inside or outside the namespace?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?LINQ's Distinct() on a particular propertyDistinct() with lambda?How do I generate a random int number?What is a NullReferenceException, and how do I fix it?The alternate style for ListBox in WPF not working as expected if the collection has some items which needs to be hiddenListBox UI not changing when item is added to ObservableCollection <string>

Can I take an upcast spell as my Mystic Arcanum?

Why does Windows store Wi-Fi passwords in a reversible format?

Semantic difference between regular and irregular 'backen'

Prevent use of CNAME record for untrusted domain

Does this VCO produce a sine wave or square wave

How to gently end involvement with an online community?

Should I stick with American terminology in my English set young adult book?

Add 2 new columns to existing dataframe using apply

Who was the most successful German spy against Great Britain in WWII, from the contemporary German perspective?

Round towards zero

Redacting URLs as an email-phishing preventative?

Higman's lemma and a manuscript of Erdős and Rado

Are game port joystick buttons ever more than plain switches? Is this one just faulty?

How to maximize the drop odds of the Essences in Diablo II?

Syntax-highlighting is getting screwed when loading long markdown files on Windows

Expressing the act of drawing

Anyone else seeing white rings in the Undead parish?

How much does Commander Data weigh?

How do proponents of Sola Scriptura address the ministry of those Apostles who authored no parts of Scripture?

Duplicate instruments in unison in an orchestra

Tex Quotes(UVa 272)

How to obtain a polynomial with these conditions?

What are the occurences of total war in the Native Americans?

Does Yeshayahu 43:10b / 43:13a imply HaShem was created?



How to distinct and count the duplicates inside a listbox?


Fluent and Query Expression — Is there any benefit(s) of one over other?How to Count Duplicates in List with LINQHow do I calculate someone's age in C#?How do I enumerate an enum in C#?Should 'using' directives be inside or outside the namespace?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?LINQ's Distinct() on a particular propertyDistinct() with lambda?How do I generate a random int number?What is a NullReferenceException, and how do I fix it?The alternate style for ListBox in WPF not working as expected if the collection has some items which needs to be hiddenListBox UI not changing when item is added to ObservableCollection <string>






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to make a listbox where i can add items to it using datagridview, the thing is i want to determine which item is duplicate and how many times it duplicate.



  • item1

  • item1

  • item2

  • item2

  • item2


output item1=2, item2=3





Here is the one that i tried which shows the last item that have been duplicate



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());









share|improve this question
































    0















    I'm trying to make a listbox where i can add items to it using datagridview, the thing is i want to determine which item is duplicate and how many times it duplicate.



    • item1

    • item1

    • item2

    • item2

    • item2


    output item1=2, item2=3





    Here is the one that i tried which shows the last item that have been duplicate



    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());









    share|improve this question




























      0












      0








      0








      I'm trying to make a listbox where i can add items to it using datagridview, the thing is i want to determine which item is duplicate and how many times it duplicate.



      • item1

      • item1

      • item2

      • item2

      • item2


      output item1=2, item2=3





      Here is the one that i tried which shows the last item that have been duplicate



      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());









      share|improve this question
















      I'm trying to make a listbox where i can add items to it using datagridview, the thing is i want to determine which item is duplicate and how many times it duplicate.



      • item1

      • item1

      • item2

      • item2

      • item2


      output item1=2, item2=3





      Here is the one that i tried which shows the last item that have been duplicate



      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#






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 19:34









      Daniel A. White

      154k40 gold badges304 silver badges383 bronze badges




      154k40 gold badges304 silver badges383 bronze badges










      asked Mar 27 at 19:33









      krljdekrljde

      13 bronze badges




      13 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          2















          Try



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





          share|improve this answer




















          • 1





            Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

            – Lews Therin
            Mar 27 at 19:45


















          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");


          This solution uses LINQ to query the listBox1's Items collection and filter out any data we don't care about.



          First, we use GroupBy to sort the items. Then, Where will filter out any items in the collection that only exist once. Select allows us to "project" the items remaining in the filtered collection into a "new form" (we use an anonymous type with an ItemName and Occurrences property to track the names of the duplicates and the number of times it appears in the collection).



          Finally, ToList converts the collection from an IEnumerable<string> 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` collection.






          share|improve this answer



























          • I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

            – krljde
            Mar 28 at 4:04











          • @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

            – Lews Therin
            Mar 28 at 22:08


















          0















          I know the Answers above will definitely work, but i can't understand it and make it work. This one works for me, where i transfer values of listbox to an array and check the duplicates inside that array.



           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






          share|improve this answer

























          • Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

            – Matt.G
            Mar 28 at 10:55














          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385167%2fhow-to-distinct-and-count-the-duplicates-inside-a-listbox%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2















          Try



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





          share|improve this answer




















          • 1





            Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

            – Lews Therin
            Mar 27 at 19:45















          2















          Try



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





          share|improve this answer




















          • 1





            Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

            – Lews Therin
            Mar 27 at 19:45













          2














          2










          2









          Try



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





          share|improve this answer













          Try



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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 at 19:43









          Matt.GMatt.G

          2,9742 gold badges4 silver badges16 bronze badges




          2,9742 gold badges4 silver badges16 bronze badges










          • 1





            Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

            – Lews Therin
            Mar 27 at 19:45












          • 1





            Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

            – Lews Therin
            Mar 27 at 19:45







          1




          1





          Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

          – Lews Therin
          Mar 27 at 19:45





          Crap, you beat me by 2 mins. I was testing mine. Upvoted :)

          – Lews Therin
          Mar 27 at 19:45













          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");


          This solution uses LINQ to query the listBox1's Items collection and filter out any data we don't care about.



          First, we use GroupBy to sort the items. Then, Where will filter out any items in the collection that only exist once. Select allows us to "project" the items remaining in the filtered collection into a "new form" (we use an anonymous type with an ItemName and Occurrences property to track the names of the duplicates and the number of times it appears in the collection).



          Finally, ToList converts the collection from an IEnumerable<string> 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` collection.






          share|improve this answer



























          • I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

            – krljde
            Mar 28 at 4:04











          • @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

            – Lews Therin
            Mar 28 at 22:08















          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");


          This solution uses LINQ to query the listBox1's Items collection and filter out any data we don't care about.



          First, we use GroupBy to sort the items. Then, Where will filter out any items in the collection that only exist once. Select allows us to "project" the items remaining in the filtered collection into a "new form" (we use an anonymous type with an ItemName and Occurrences property to track the names of the duplicates and the number of times it appears in the collection).



          Finally, ToList converts the collection from an IEnumerable<string> 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` collection.






          share|improve this answer



























          • I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

            – krljde
            Mar 28 at 4:04











          • @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

            – Lews Therin
            Mar 28 at 22:08













          2














          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");


          This solution uses LINQ to query the listBox1's Items collection and filter out any data we don't care about.



          First, we use GroupBy to sort the items. Then, Where will filter out any items in the collection that only exist once. Select allows us to "project" the items remaining in the filtered collection into a "new form" (we use an anonymous type with an ItemName and Occurrences property to track the names of the duplicates and the number of times it appears in the collection).



          Finally, ToList converts the collection from an IEnumerable<string> 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` collection.






          share|improve this answer















          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");


          This solution uses LINQ to query the listBox1's Items collection and filter out any data we don't care about.



          First, we use GroupBy to sort the items. Then, Where will filter out any items in the collection that only exist once. Select allows us to "project" the items remaining in the filtered collection into a "new form" (we use an anonymous type with an ItemName and Occurrences property to track the names of the duplicates and the number of times it appears in the collection).



          Finally, ToList converts the collection from an IEnumerable<string> 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` collection.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 28 at 22:23

























          answered Mar 27 at 19:45









          Lews TherinLews Therin

          3,0681 gold badge16 silver badges43 bronze badges




          3,0681 gold badge16 silver badges43 bronze badges















          • I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

            – krljde
            Mar 28 at 4:04











          • @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

            – Lews Therin
            Mar 28 at 22:08

















          • I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

            – krljde
            Mar 28 at 4:04











          • @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

            – Lews Therin
            Mar 28 at 22:08
















          I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

          – krljde
          Mar 28 at 4:04





          I can't understand how to make this work I'm pretty new to c# and i'm using this to output on a Form in visual studio. Can you explain how your code works?

          – krljde
          Mar 28 at 4:04













          @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

          – Lews Therin
          Mar 28 at 22:08





          @krljde Sorry, I quickly wrote that and had it write the output to the Console. I edited my answer so now it does a message box like your original example. I'll also add a short explanation.

          – Lews Therin
          Mar 28 at 22:08











          0















          I know the Answers above will definitely work, but i can't understand it and make it work. This one works for me, where i transfer values of listbox to an array and check the duplicates inside that array.



           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






          share|improve this answer

























          • Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

            – Matt.G
            Mar 28 at 10:55
















          0















          I know the Answers above will definitely work, but i can't understand it and make it work. This one works for me, where i transfer values of listbox to an array and check the duplicates inside that array.



           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






          share|improve this answer

























          • Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

            – Matt.G
            Mar 28 at 10:55














          0














          0










          0









          I know the Answers above will definitely work, but i can't understand it and make it work. This one works for me, where i transfer values of listbox to an array and check the duplicates inside that array.



           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






          share|improve this answer













          I know the Answers above will definitely work, but i can't understand it and make it work. This one works for me, where i transfer values of listbox to an array and check the duplicates inside that array.



           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







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 4:32









          krljdekrljde

          13 bronze badges




          13 bronze badges















          • Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

            – Matt.G
            Mar 28 at 10:55


















          • Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

            – Matt.G
            Mar 28 at 10:55

















          Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

          – Matt.G
          Mar 28 at 10:55






          Linq Query Expressions is used in this answer, where as Linq Fluent Expressions is used in the other answers. Ref. you could still avoid using the list variable and the for loop by simply changing the code to var r = from b in listBox1.Items.Select(x => x.ToString())

          – Matt.G
          Mar 28 at 10:55


















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385167%2fhow-to-distinct-and-count-the-duplicates-inside-a-listbox%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현