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

Majid picture Majid · Jul 24, 2013 · Viewed 72k times · Source

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?

Answer

Rodrigo L&#243;pez picture Rodrigo López · May 12, 2014

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