43

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?


IEnumerable<Book> books = new List<Book>();
4

5 回答 5

99

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>();
于 2014-05-12T19:46:14.317 回答
26
IEnumerable<Book> books = new List<Book>();
于 2013-07-24T10:14:23.073 回答
4

Personally I'd just go with:

IEnumerable<Book> books = new Book[0];

rather than using a List.

于 2013-07-24T10:26:10.070 回答
4

This is what you are trying to do:

IEnumerable<Book> books = Enumerable.Empty<Book>();
books = books.Concat(context.Books.AsEnumerable().Where(b => someCondition));

Alternatively you can do this if you like to start from null:

IEnumerable<Book> books = null;
var moreBooks = context.Books.AsEnumerable().Where(b => someCondition);
books = books == null ? moreBooks : books.Concat(moreBooks);

...although I have several question as to why you want / need to do things this way.

于 2016-04-04T02:12:32.477 回答
1

You need create books as a IEnumerable empty object like List, but need remember to call, after loop, ToList() on books. For example:

        IEnumerable<int> books = new List<int>();
        IEnumerable<int> books2 = new int[] { 1, 2, 3, 4 };


        foreach (int b in books2)
            if (b > 2)
                books = (new[] { b }).Concat(books);

        books = books.ToList();
于 2013-07-24T10:25:02.600 回答