Count repetition of data starting with specific value in a DataGridView

Primer 41 Reputation points
2022-04-09T14:36:10.267+00:00

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!

Developer technologies | Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-04-11T02:05:27.58+00:00

    @Primer , 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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.