C# 检查空引用时发生linq NullReferenceException
我有以下LINQ查询:C# 检查空引用时发生linq NullReferenceException,c#,linq-to-objects,C#,Linq To Objects,我有以下LINQ查询: List<FileInputItem> inputList = GetInputList(); var results = from FileInputItem f in inputList where ( Path.GetDirectoryName(f.Folder).ToLower().Trim() == somePath || Path.GetDirectoryName(f.Folde
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;
我对LINQ对象还不熟悉,所以我可能缺少一些基本的东西。这是怎么回事?可能存在FileInputItem.Folder为null的情况(这会导致“Path.GetDirectoryName(f.Folder.ToLower().Trim()”异常),并且这些情况恰好与FileInputItem.Expression为null的情况一致
尝试将“f.Folder!=null”添加到where子句的开头,看看这是否解决了问题。如果是这样,请确定当文件夹为null时您希望如何处理这些情况。可能存在FileInputItem.Folder为null的情况(这将导致“Path.GetDirectoryName(f.Folder.ToLower().Trim()”异常),并且这些情况恰好与FileInputItem.Expression为null的情况一致
尝试将“f.Folder!=null”添加到where子句的开头,看看这是否解决了问题。如果是这样,请确定当文件夹为空时您希望如何处理这些情况。您也可以尝试String.IsNullOrEmpty(f.Expression)您也可以尝试String.IsNullOrEmpty(f.Expression)这有帮助吗
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;
List inputList=GetInputList();
var results=来自inputList中的FileInputItem f
其中f.文件夹!=null&&f。表达式==null
让path=path.GetDirectoryName(f.Folder.ToLower().Trim()
其中path==somePath | | path=someOtherpath
选择f;
这有帮助吗
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;
List inputList=GetInputList();
var results=来自inputList中的FileInputItem f
其中f.文件夹!=null&&f。表达式==null
让path=path.GetDirectoryName(f.Folder.ToLower().Trim()
其中path==somePath | | path=someOtherpath
选择f;
是否首先计算&的第一部分?完全正确。我天真地认为文件夹永远不会为空。谢谢@brickner,这是正确的。我已经更新了帖子,说明它应该在开头。我实际上想说的是,如果Path.GetDirectoryName(f.Folder).ToLower().Trim()是首先计算的,那么f为什么会为null?是不是首先计算了&&的第一部分?完全正确。我天真地认为文件夹永远不会为空。谢谢@brickner,这是正确的。我已经更新了帖子,说明它应该在开头。我实际上想说的是,如果首先计算Path.GetDirectoryName(f.Folder).ToLower().Trim(),f为什么会为null?这实际上是我最初使用的。这实际上是我最初使用的。