I tried this code for adding b
to books
:
IEnumerable<Book> books =null; foreach (Book b in context.Books.AsEnumerable()) if (someConditions) books = books.Concat(new[] {b});
but gives me this error on last line of code:
System.ArgumentNullException: Value cannot be null. Parameter name: first
it seems that null
Collection
could not concatenated. I use EF,so how should I initialize my Collection
that have no thing in it and I could concatenate to it?
Empty<T> actually returns an empty array of T (T[0]), with the advantage that the same empty array is reused. Note that this approach is not ideal for non-empty arrays, because the elements can be modified (however an array can't be resized, resizing involves creating a new instance).
What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
It seams all you want to do is filter your context.Books by some criteria.
IEnumerable<Book> books = context.Books.Where(b => someConditions);
If you still need the empty IEnumerable you can just call Enumerable.Empty():
IEnumerable<Book> books = Enumerable.Empty<Book>();
IEnumerable<Book> books = new List<Book>();
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