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>
?
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.
Unfortunately, List<T>. AddRange isn't defined in any interface.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With