Search code examples
c#collectionsienumerable

How to add an item to an IEnumerable


In C#

IEnumerable<MyModel> test = _blah.tolist();

Now I can loop through test, but how do I add an item?

Please do not tell me that it makes no sense to add an item, I've already seen that post.

What I want to know is, if I loop through 10 items, how do I put one more on so it loops through 11 items?

Also there is no .Add() method


Solution

  • IEnumerable is an interface. You can't use Add() on an IEnumerable because they're not required to implement an Add() method. See the IEnumerable documentation on MSDN.

    Instead, create a generic list which inherits from the interface IList. Types that use the IList interface must implement Add().

    List<MyBlahType> test = _blah.tolist();
    test.Add(new MyBlahType());
    

    If you still want to use an interface to avoid a concrete type, then use IList directly.

    IList<MyBlahType> test= _blah.tolist();
    test.Add(new MyBlahType());
    

    By the way, it's usually considered poor styling to start variable/type names with underscores and to not use proper capitalization. The preferred style in C# is to use PascalCase or camelCase for capitalization.