LINQ provides extension methods on any type that implements IEnumerable<T> which is defined in the System.Collections.Generic
namespace and is the general interface you use for anything that stores sets of items including List<T> and Queue<T>.
LINQ has an extension method Count that returns the # of items in the collection by enumerating them and adding up the total. As such any IEnumerable<T>
implementation has this method available to it. It looks like an instance method but is in fact a static method on the Enumerable
class. Read about extension methods to understand how this works.
Enumerable
is defined in the System.Linq
namespace along with a lot of the other LINQ-based types. Therefore by including that namespace you have access to the extension methods.
using System;
using System.Collections.Generic;
using System.Linq;
public class SomeClass
{
public void DoWork ()
{
Queue<int> numbers = new Queue<int>();
for (int index = 1; index <= 10; ++index)
numbers.Enqueue(index);
int count = numbers.Count(); //Extension method Enumerable.Count()
//Note: List<T> has a Count property which does the same thing, but only for List<T>
}
}
If you are compiling using .NET 6+ AND your project has implicit usings enabled then the compiler automatically includes some of the more commonly needed namespaces automatically at the top of your source files including: System
, System.Collections.Generic
and System.Linq
. As such this eliminates the need for you to have these commonly needed namespaces explicitly listed in every source file you have. The earlier code can be rewritten without them and the compiler will generate the same exact code.
public class SomeClass
{
public void DoWork ()
{
Queue<int> numbers = new Queue<int>();
for (int index = 1; index <= 10; ++index)
numbers.Enqueue(index);
int count = numbers.Count(); //Extension method Enumerable.Count()
//Note: List<T> has a Count property which does the same thing, but only for List<T>
}
}
By default when you create a NET 6+ project then implicit usings are enabled in the project. You can disable them in the project file but there probably isn't a good reason to do so.