1

I'm tallying a row in my access database. My databases contain movie company,movies produced by companies and the amount of movies sold. There is more info in the database than I mentioned, but for this problem I'm only looking at two columns. The movie company and the movies produced by that company. One column is called company and the other is called Movie. I need to count every movie that was produced by the movie company. I counted six different Movie companies in the database. My goal is to simply display the movie company and the number movies it produced in a listbox.

I have two big problems. 1. My result won't display in the listbox. 2 According to the good people who looked at my code. The program is not counting anything. Here is example of what I want to display

Company #Movies

Paramount 4

20thCenturyfox 8

LucasFilm 6

etc.

What I'm thinking is created a nested foreach loop and for every movie that is produced by a certain company add it to the listbox.

private void tabP3_Click(object sender, EventArgs e)
    {
       foreach (DataRowView row in bindingSource1.List)
        {
            foreach (DataRowView row2 in bindingSource1.List)
            {
              if(((String)row2["Company"]).Equals(row["Movie"]))
                {
                int count = 0;
                count++;
                lbCompany.Items.Add((String.Format("{0,5}", count)));
                }

            }

        }

    }

2 Answers2

0

Why don't you use Linq to achieve the solution? That's what I would do, in the first place, to tackle your requirement.

The following is taken from this post. "data" should be your collection... here you will get a new type that contains 2 fields (which you can edit/change per your convenience). You may also want to remove the OrderBy.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric)
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}
Community
  • 1
  • 1
Veverke
  • 9,208
  • 4
  • 51
  • 95
0

First it is most certain you never entering the if statement since you are comparing for equality to different objects. One object of datatype string: (String)row2["Company"] and one object of datatype System.Data.DataRow row["Movie"]. Further in each iteration you set counter back to zero. So try:

 int count = 0;
 foreach (DataRowView row in bindingSource1.List)
        {
            foreach (DataRowView row2 in bindingSource1.List)
            {
              if((row2["Company"].ToString()).Equals(row["Movie"].ToString()))
                {               
                count++;
                lbCompany.Items.Add((String.Format("{0}", count)));
                }

            }

        }
apomene
  • 14,282
  • 9
  • 46
  • 72