Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an item to an IEnumerable [duplicate]

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

like image 950
user1854438 Avatar asked Apr 25 '14 15:04

user1854438


3 Answers

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.

like image 53
mason Avatar answered Oct 17 '22 10:10

mason


Use LINQ-to-object's Concat to build a new IEnumerable that iterates the first one and then the second one:

IEnumerable<MyModel> test = _blah.tolist();
IEnumerable<MyModel> second = new[] { theItem };
IEnumerable<MyModel> elevenItems = test.Concat(second);
like image 36
Jacob Krall Avatar answered Oct 17 '22 09:10

Jacob Krall


If you've called ToList() on an IEnumerable<T>, the return type will be a List<T>. If the type of your variable were List<T> rather than IEnumerable<T>, you would be able to do whatever you wanted to the list you received, including adding items to it, just like you could do with any other list. Note that the newly made list would be "detached" from the original IEnumerable<T>, so that adding, removing, rearranging, or replacing items in one would not affect the other. Note also, however, that a list of mutable-reference-type items does not hold items, but merely identifies them. If one has an IEnumerable<Car> myCars, and the third item is "Car#24601", then myCars.ToList()[2].Color = CarColors.Red; then the third item in the original list (i.e. Car #24601) will be painted red.

like image 2
supercat Avatar answered Oct 17 '22 10:10

supercat