Home > Backend Development > C++ > How Can I Add Items to an IEnumerable?

How Can I Add Items to an IEnumerable?

Barbara Streisand
Release: 2024-12-29 21:43:40
Original
154 people have browsed it

How Can I Add Items to an IEnumerable?

Adding Items to an IEnumerable

Many developers seek a method like items.Add(item) for adding elements to an IEnumerable collection. However, this cannot be done because an IEnumerable does not necessarily represent a mutable collection. It might not even represent a collection at all.

For example, consider the following method:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}
Copy after login

This method generates an IEnumerable by reading lines from the console. Attempting to call Add("foo") on the resulting collection would raise an exception because it's not supported on this IEnumerable implementation.

Instead, you can use the Enumerable.Concat method to append new items to an IEnumerable. For the example above, you could create a new IEnumerable that includes both the lines from the console and a new item "foo" as follows:

items = items.Concat(new[] { "foo" });
Copy after login

This approach creates a new IEnumerable that includes the items from both the original IEnumerable and the new item. Note that it does not modify the original collection.

The above is the detailed content of How Can I Add Items to an IEnumerable?. 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