Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ中的参数,其中变为null,它不';我不明白。为什么会这样?_C#_Linq - Fatal编程技术网

C# LINQ中的参数,其中变为null,它不';我不明白。为什么会这样?

C# LINQ中的参数,其中变为null,它不';我不明白。为什么会这样?,c#,linq,C#,Linq,我写C#和LINQ查询已经很长时间了。我想浏览一个临时列表,查找1个字段(命名模型)上的匹配值。规范规定,如果有匹配的模型,则不会将其添加到列表中。所以,我删除了重复的模型,只将唯一的模型放入列表中,然后返回。下面是我编写的函数: private List EnsureInstrumentModelListUnique(列出仪表模型) { var tmpList=新列表(); if(instrumentModels==null | | instrumentModels.Count t.Model

我写C#和LINQ查询已经很长时间了。我想浏览一个临时列表,查找1个字段(命名模型)上的匹配值。规范规定,如果有匹配的模型,则不会将其添加到列表中。所以,我删除了重复的模型,只将唯一的模型放入列表中,然后返回。下面是我编写的函数:

private List EnsureInstrumentModelListUnique(列出仪表模型)
{
var tmpList=新列表();
if(instrumentModels==null | | instrumentModels.Count t.Model==Model.FirstOrDefault();
//如果它不在那里,就把它放进去
if(rec==null)
{
tmpList.Add(rec);
}
}
}
返回tmpList;
}
在崩溃之前,它与
循环一起运行了3次。它在
tmpList.Where(t=>t.Model==Model.FirstOrDefault()
中的
t.Model
上崩溃,声称
t
为空

我不明白在循环的第三次迭代中,
t
如何为空。
instrumentModels
来自的表中有5条记录。所有记录在模型列中都有一些内容

以下是InstrumentModel的定义,为简洁起见,仅包含相关列:

[表(“app.InstrumentModel”)]
[DebuggerDisplay(“ID={ID},Model=={Model},Inactive=={Inactive}”)]
公共部分类模型
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Usage”,“CA2214:DoNotCallOverridableMethodsInConstructors”)]
公共工具模型()
{
Instruments=新的HashSet();
PersonnelCertifications=新哈希集();
}
[关键]
公共长ID{get;set;}
[必需]
[行政长官(30)]
公共字符串模型{get;set;}
}

我正在使用WPF、.NET Framework 4.5.2,与2019年相比

正如@madreflection所指出的,问题在于:

//check to see if model is somewhere in the list
var rec = tmpList.Where(t => t.Model == model).FirstOrDefault();

//if it isn't there, put it in
if (rec == null)
{
    tmpList.Add(rec);
}
在这种情况下,我相信您应该在插入
模型时插入
rec

使用
Any
,代码更简单。如果您这样做的话,就没有空变量可以混淆

bool found = tmpList.Any(t => t.Model == model);

if (!found)
{
    tmpList.Add(model);
}

如果(rec==null){tmpList.Add(rec);}
被注释为“如果它不在那里,就把它放进去”。我想说的是,这样的评论实际上是有害的,因为它们会阻止你阅读你写的东西。谢谢你,John Wu和madreflection。我现在明白我的错误了。我离它太近了,所以我没有看到它。需要其他人的眼睛来告诉我。现在很明显。另外,感谢您告知我有关
任何
短语的信息。我认为这类似于SQL
存在