基于最大值的Linq c#

本文关键字:Linq 最大值 | 更新日期: 2023-09-27 18:04:03

我从数据库中获取数据,得到以下结构。按InputFileIdFilename分组,只选择Failed的最大值

InputFileId = 12, FileName = "Filename_12", Failed = false
InputFileId = 13, FileName = "Filename_13", Failed = false  
InputFileId = 13, FileName = "Filename_13", Failed = true   

现在我只想看到这个结果:

InputFileId = 12, FileName = "Filename_12", Failed = false
InputFileId = 13, FileName = "Filename_13", Failed = true   
到目前为止,我的Linq查询是:
Files = (this.InputFileStatusService.GetFilesUploadedByDay(StartOfDay(SelectedDate), EndOfDay(SelectedDate), this.Deal.Id))
            .Where(a => a.InputFileId > 0)
            .GroupBy(m => new { m.InputFileId, m.FileName, Failed = m.Failed ? 1 : 0 })
            .Select(m => new 
            { 
                InputFileId = m.Key.InputFileId, 
                FileName = m.Key.FileName,
                Failed = m.Max(x=>x.Failed) 
            }).ToList();

但是这不起作用,有人有解决办法吗?

基于最大值的Linq c#

应该足以将Max替换为Any

Failed = m.Any(x => x.Failed) 

并删除

中的Failed = m.Failed ? 1 : 0
.GroupBy(m => new { m.InputFileId, Failed = m.Failed ? 1 : 0 })

由于这些列似乎彼此对应,您可以考虑为m.FileName也添加一个分组

您按Failed分组,因此在每个组中您将有1个项目-并且它的Max(Failed)将与密钥中相同。

仅按InputFieldId分组,检查Failed在组中Any的值是否为true:

Files = (this.InputFileStatusService.GetFilesUploadedByDay(StartOfDay(SelectedDate), EndOfDay(SelectedDate), this.Deal.Id))
            .Where(a => a.InputFileId > 0)
            .GroupBy(m => new { m.InputFileId, m.FileName })
            .Select(m => new 
            { 
                InputFileId = m.Key.InputFileId, 
                FileName = m.Key.FileName, 
                Failed = m.Any(x => x.Failed) 
            }).ToList();