문제

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?

도움이 되었습니까?

해결책

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

Personally I'd just go with:

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

rather than using a List.

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.

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top