views:

81

answers:

3

I have the following LINQ query:

List<FileInputItem> inputList = GetInputList();
var results = from FileInputItem f in inputList
              where ( Path.GetDirectoryName(f.Folder).ToLower().Trim() == somePath
                     || Path.GetDirectoryName(f.Folder).ToLower().Trim() == someOtherPath ) 
                    && f.Expression == null
             select f;

Every time this query is executed, it generates a NullReferenceException. If I remove the condition f.Expression == null or change it to f.Expression != null, the query executes normally (giving the wrong results, of course).

The relevant bits of FileInputItem look like this:

[Serializable]
public class FileInputItem
{
    [XmlElement("Folder")]
    public string Folder { get; set; }

    [XmlElement("Expression")]
    public string Expression { get; set; }

    /*SNIP.  Irrelevant properties */
}

I'm new to LINQ to objects, so I'm probably missing something fundamental here. What's the deal?

+3  A: 

There are probably cases where FileInputItem.Folder is null (which would cause an exception with "Path.GetDirectoryName(f.Folder).ToLower().Trim()"), and those cases happen to coincide with the cases where FileInputItem.Expression is null.

Try adding "f.Folder != null" to the beginning of your where clause and see if that fixes the issue. If so, determine how you want to handle those cases when Folder is null.

Mike Mooney
brickner
Exactly right. I had naively assumed that Folder would never be null.
Odrade
Thanks @brickner, that is correct. I've updated the post to state it should be at the beginning
Mike Mooney
What I've actually tried to say is how come f be null if Path.GetDirectoryName(f.Folder).ToLower().Trim() is evaluated first?
brickner
A: 

You could also try String.IsNullOrEmpty(f.Expression)

MUG4N
That's actually what I was using initially.
Odrade
A: 

Does this help?

List<FileInputItem> inputList = GetInputList();
var results = from FileInputItem f in inputList
              where f.Folder != null && f.Expression == null
              let path = Path.GetDirectoryName(f.Folder).ToLower().Trim()
              where path == somePath || path = someOtherpath
              select f;
Foole