"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 > Can IEnumerable Collections Be Augmented Like Lists?

Can IEnumerable Collections Be Augmented Like Lists?

Posted on 2025-02-26
Browse:474

Can IEnumerable Collections Be Augmented Like Lists?

Can IEnumerable Collections Be Augmented Like Lists?

IEnumerable collections represent sequences of elements that may or may not be mutable. Unlike lists, IEnumerable collections do not inherently support item addition.

When attempting to add items to an IEnumerable collection, such as in the provided example, it is actually inefficient. The ToList() method converts the IEnumerable to a List, allowing item addition. However, the original IEnumerable remains unchanged, resulting in a collection with only one element.

Is there an alternative to items.Add(item)?

No, there is no direct equivalent to items.Add(item) in IEnumerable. However, you can create a new IEnumerable that includes both the original items and the new item. This technique relies on the Enumerable.Concat method:

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

This approach creates a non-mutable IEnumerable that incorporates all elements from the original collection and the added item. Additionally, it ensures that any future changes to the original collection are reflected in the new IEnumerable.

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