0

I get null reference with the following code, how do I properly assign the result variable to the new list:

var result = from loan in loansList
             where loan.supervisorID == "1188775"
             select loan;

List<Loan> ayumiLoans = new List<Loan>();

ayumiLoans = result as List<Loan>;

foreach (Loan aLoan in ayumiLoans )
{
    aLoan.printLoan();
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Coder
  • 121
  • 9

3 Answers3

2

result is not of type List<Loan>; the only we can say is that it implements IEnuemrable<Loan>. That's why

 result as List<Loan>;

is null. Then you assign null to ayumiLoans

ayumiLoans = result as List<Loan>; // ayumiLoans is null

And you get the error when trying to loop over null. Try either

var result =   from loan in loansList
              where loan.supervisorID == "1188775"
             select loan;

List<Loan> ayumiLoans = new List<Loan>();

// Add all result items into ayumiLoans
ayumiLoans.AddRange(result);

Or

var result =   from loan in loansList
              where loan.supervisorID == "1188775"
             select loan;

// Materialize result as List<Loan> 
List<Loan> ayumiLoans = result.ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

I think you should be able to just do it this way:

List<Loan> ayumiLoans = new List<Loan>(result);

Otherwise Im sure Dmitry got it right, he helped me often already :'D

Benyom
  • 75
  • 7
1

There is a bit more efficient List<T>.FindAll(Predicate<T>) Method for that :

 List<Loan> ayumiLoans = loansList.FindAll(loan => loan.supervisorID == "1188775");
Slai
  • 22,144
  • 5
  • 45
  • 53