snippetcsharpCritical
How can I add an item to a IEnumerable<T> collection?
Viewed 0 times
collectionhowienumerableaddcanitem
Problem
My question as title above. For example
but after all it only has 1 item inside. Can we have a method like
IEnumerable 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?Solution
You cannot, because
What you can do, however, is create a new
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).
IEnumerable 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 ReadLines()
{
string s;
do
{
s = Console.ReadLine();
yield return s;
} while (!string.IsNullOrEmpty(s));
}
IEnumerable 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).
Code Snippets
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??items = items.Concat(new[] { "foo" });Context
Stack Overflow Q#1210295, score: 593
Revisions (0)
No revisions yet.