Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize IEnumerable<Object> that be empty and allow to Concat to it?

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?

like image 893
Majid Avatar asked Jul 24 '13 10:07

Majid


People also ask

How do I return empty IEnumerable?

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).

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

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");

How do I return an IEnumerable object in C#?

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.

What is IEnumerable string?

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.


2 Answers

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>(); 
like image 69
Rodrigo López Avatar answered Sep 22 '22 10:09

Rodrigo López


IEnumerable<Book> books = new List<Book>(); 
like image 45
chris.ellis Avatar answered Sep 22 '22 10:09

chris.ellis