-3

In my code, I am attempting to output the amount of items in my movie list from a console command, but I'm not entirely sure on how I'd be able to grab the amount of items from the list. The list is originally created as a private list, but I have a property making it an IEnumerable list, shown below.

public IEnumerable<Movie> Movies
        {
            get
            {
                return this.movies;
            }
        }

How would I be able to count how many items are within the list that is given by the property?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Possible duplicate of [Howto: Count the items from a IEnumerable without iterating?](http://stackoverflow.com/questions/168901/howto-count-the-items-from-a-ienumerablet-without-iterating) – Simon Bosley Mar 23 '17 at 16:27
  • Possible duplicate of [IEnumerable doesn't have a Count method](http://stackoverflow.com/questions/2659290/ienumerable-doesnt-have-a-count-method) – Renats Stozkovs Mar 23 '17 at 16:38

2 Answers2

4

What is the problem with calling the Count method:

Movies.Count();

You will need System.Linq namespace.

Sadique
  • 22,572
  • 7
  • 65
  • 91
0

If your collection actually is a list you can cast it back instead of using the Count()-method, that IEnumerable provides. Not sure if List.Count() will internally call List.Count - but I expect it to. Anyway here´s the code for the cast:

public IEnumerable<Movie> Movies
{
    get
    {
        return this.movies;
    }
}

var theList = instance.Movies as IList<Movie>();
if (theList != null) 
    count = theList.Count;
else 
    count = instance.Movies.Count();
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111