Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an item to a IEnumerable<T> collection?

My question as title above. For example

IEnumerable<T> items = new T[]{new T("msg")}; items.ToList().Add(new T("msg2")); 

but after all it only has 1 item inside. Can we have a method like items.Add(item) like the List<T>?

like image 445
ldsenow Avatar asked Jul 31 '09 01:07

ldsenow


People also ask

How do I add something to ICollection?

ICollection is an interface, you can't instantiate it directly. You'll need to instantiate a class that implements ICollection ; for example, List<T> . Also, the ICollection interface doesn't have an Add method -- you'll need something that implements IList or IList<T> for that.

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

Is IEnumerable a collection?

IEnumerable<T> is an interface that represents a sequence. Now; collections can usually be used as sequences (so... List<T> implements IEnumerable<T> ), but the reverse is not necessarily true. In fact, it isn't strictly required that you can even iterate a sequence ( IEnumerable<T> ) more than once.


1 Answers

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines() {      string s;      do      {           s = Console.ReadLine();           yield return s;      } while (!string.IsNullOrEmpty(s)); }  IEnumerable<string> lines = ReadLines(); lines.Add("foo") // so what is this supposed to do?? 

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

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

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

like image 102
Pavel Minaev Avatar answered Oct 03 '22 07:10

Pavel Minaev