"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Add Items to an IEnumerable?

How Can I Add Items to an IEnumerable?

Posted on 2025-02-07
Browse:224

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 ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

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" });

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3