Walter Walter - 3 months ago 13
C# Question

Linq C# based on max value

I fetch data from the database, which results in the following structure. Group by

InputFileId
and
Filename
and only select the maximum value of
Failed
.

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


Now I only want to see this result :

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


The Linq query I have so far is:

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();


But this isn't working, does anyone have a solution for this?

Answer

Should be enough to replace Max with Any

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

And remove the Failed = m.Failed ? 1 : 0 in

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

Since those columns seem to correspond to each other you might consider to add a grouping for m.FileName aswell.