question

Primer-9267 avatar image
0 Votes"
Primer-9267 asked Primer-9267 commented

Count repetition of data starting with specific value in a DataGridView

I have dataGridView1 containing two columns, Col1 and Col2, both contain duplicate values.

Column1 | Column2


   2515 | 1105
   1105 | 2515
   3800 | 2208
   2515 | 1105
   2508 | 3800

I need to count repetition of values from both columns by selecting only values starting with 25 then show the result in dataGridView2 which consists of Columns: Id, Value, and Repetition, after clicking on a button.

I tried the following but miss the condition to select and count only values start with 25:

             var s1 = dt.AsEnumerable().Select(r => r.Field<string>("Column1")).ToList();
             var s2 = dt.AsEnumerable().Select(r => r.Field<string>("Column2")).ToList();
    
             List<string> list = new List<string>();
             list.AddRange(s1);
             list.AddRange(s2);
             var result = list.GroupBy(x => x)
             .Select(g => new { Value = g.Key, Count = g.Count() })
             .OrderByDescending(x => x.Count);
             int count = 1;
             dataGridView2.Columns.Add("Id", "");
             dataGridView2.Columns.Add("Value", "");
             dataGridView2.Columns.Add("Repetition", "");
    
             foreach (var item in result)
             {
                 dataGridView2.Rows.Add(count, item.Value, item.Count);
                 count++;
             }

How can I count values start with 25** from datagridview1 and show them in dataGridView2?

Appreciate your help!


windows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JackJJun-MSFT avatar image
1 Vote"
JackJJun-MSFT answered Primer-9267 commented

@Primer-9267, Welcome to Microsoft Q&A, you could try the following code to filter the condidtion that values start with 25.

  foreach (var item in result)
             {
                 if(item.Value.StartsWith("25"))
                 {
                     dataGridView2.Rows.Add(count, item.Value, item.Count);
                     count++;
                 }
                  
             }

Result:

191636-image.png



Best Regards,
Jack


If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


image.png (8.4 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you so much @JackJJun-MSFT, Your answer works properly for me!
Thanks for help!

0 Votes 0 ·