-2

this code :

var allSubjectsForAStudent =    GetAllSubjects<Subject>(studentId);

returns an

IEnumerable<Subject> 

and I can see bunch of subjects returned in the debugger.

Want to check for a particular Subject doing a case insensitive comparison.

This is the code that I have:

var studentSubjects = allSubjectsForAStudent.Where(s => s.Name.Equals(subjectName, StringComparison.CurrentCultureIgnoreCase));

'subjectName' is a parameter that the method will recieve.

When this line executes I get the 'Object not set to an instance of an object' error.

So what I want to do is a CASE INSENSITIVE search and return the first item when there are more than one and return an empty collection when there are none.

Any clues?

Edit 1

The answers suggest that there can be an entry in the first collection which might have a 'null'. While the observation is true the program makes sure that the 'Subject Name' can not be a null value. Hope this helps.

Thanks in advance.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Codehelp
  • 4,157
  • 9
  • 59
  • 96
  • Is there an item in the collection that's name is `null`? That's the most likely cause. – MarcinJuraszek Jun 01 '15 at 06:12
  • 1
    I'm tempted to close as duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)... but I'm compelled to tell you that you haven't shown us enough code to even diagnose a problem. The problem is in how you got your subjects. Something there is `null` but there's no way of us knowing because you haven't shown us any of that code. – Jeff Mercado Jun 01 '15 at 06:13

2 Answers2

0

You could try:

var studentSubjects = allSubjectsForAStudent.Where(s => !string.IsNullOrWhiteSpace(s.Name) && s.Name.ToUpperInvariant() == subjectName.ToUpperInvariant()).FirstOrDefault();

This will either set studentSubjects to null or the first instance in the IEnumerable that matches.

You're getting a NullReferenceException when you call

s.Name.Equals(subjectName)

for an object where s.Name is null.

GeorgDangl
  • 2,146
  • 1
  • 29
  • 37
0

It will :

if(allSubjectsForAStudent!=null && !string.IsNullorEmpty(subjectName))
var studentSubjects = allSubjectsForAStudent.Where(s => s.Name.Equals(subjectName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
Thirisangu Ramanathan
  • 614
  • 1
  • 11
  • 20