Skip to main content
 首页 » 编程设计

c#之LINQ之选择最小值,仅当集合不为空时

2024年01月31日26cloudgamer

我有以下(简化的)模型:

public class ClockinReport_PerMachine 
{ 
    public ObservableCollection<Clockin_Categories> Categories { get; set; } 
} 
public class Clockin_Categories 
{ 
    public ObservableCollection<ClockinReport_Day> Report { get; set; } 
} 
public class ClockinReport_Day 
{ 
    public DateTime Day { get; set; } 
} 

然后在我的 ViewModel 中有以下内容:

public ObservableCollection<ClockinReport_PerMachine> MachineReport {get;set;} 

逻辑如下:

  • 你有多台机器
  • 每台机器都有我们报告的几个类别(例如,错误 - 没有纸张,错误 - 没有墨水,......只是一个例子)
  • 在每个类别下,都有日常事件,除了其他事情外,我们会跟踪问题发生时的确切日期时间

我有以下脚本,它从所有 MachineReports

返回最小日期时间
PeriodFrom = MachineReport.Min(n => n.Categories.Min(x => x.Report.Min(z => z.Day))); 

此 LINQ 遍历所有机器,遍历所有类别并查看报告并检查最小日期时间是多少(至少我认为它是这样做的)。

当 Categories 不包含任何元素时,就会出现问题。然后它返回一个错误,提示 Sequence contains no elements。

如果没有元素,我如何更改我的 LINQ,以便它忽略类别?

最终:

最后检查集合是否不为空对我不起作用,因为我的集合包含 0 个元素(它在启动时初始化)。因此,我不得不对以下内容稍作修改:

PeriodFrom = MachineReport.Min(n => n.Categories.Where(b=>b.Report.Count>0).Min(x => x.Report.Max(z => z.Day))); 

请您参考如下方法:

PeriodFrom = MachineReport.Min(n => n.Categories. 
                                      Where(c => c != null). 
                                      Min(x => x.Report.Min(z => z.Day)));