linq NullReferenceException while checking for null reference
I have the following LINQ query:
L开发者_高级运维ist<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?
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.
You could also try String.IsNullOrEmpty(f.Expression)
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;
精彩评论