Adding Items to an IEnumerable
Many developers seek a method like items.Add(item) for adding elements to an IEnumerable
For example, consider the following method:
IEnumerable<string> 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.
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!