Home > Backend Development > C++ > How to Get the Count of an IEnumerable without Iteration?

How to Get the Count of an IEnumerable without Iteration?

Barbara Streisand
Release: 2024-12-26 06:50:13
Original
365 people have browsed it

How to Get the Count of an IEnumerable without Iteration?

Obtaining the Count of IEnumerable without Iteration

In certain scenarios, developers may need to ascertain the count of elements within an IEnumerable collection without the necessity of iterating through it. This arises, for instance, when a progress status needs to be displayed by indicating the current and total number of items being processed.

However, IEnumerable lacks an inherent method to retrieve the count without iteration. This is a deliberate design choice, as IEnumerable embraces lazy evaluation, only generating elements as they are requested.

Solution: Utilizing ICollection

To circumvent the limitation of IEnumerable, developers can leverage ICollection, which inherits from IEnumerable and includes a Count property. By casting the IEnumerable instance to ICollection, the Count property can be directly accessed, providing the number of elements without requiring iteration.

Example:

Consider the following code:

private IEnumerable<string> Tables
{
    get
    {
        yield return "Foo";
        yield return "Bar";
    }
}
Copy after login

To determine the count of tables without iterating, the code can be modified as follows:

var count = ((ICollection<string>)Tables).Count;
Copy after login

The cast to ICollection enables direct access to the Count property, yielding the value of 2, indicating the number of tables in the collection without the need for iteration.

The above is the detailed content of How to Get the Count of an IEnumerable without Iteration?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template