0

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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

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

1 Comment

That's actually what I was using initially.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.