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:
IEnumerableReadLines() { 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.
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