LINQ-Max, where the condition

I have a TaskWeekUI class with this definition:

public class TaskWeekUI { public Guid TaskWeekId { get; set; } public Guid TaskId { get; set; } public Guid WeekId { get; set; } public DateTime EndDate { get; set; } public string PersianEndDate { get; set; } public double PlanProgress { get; set; } public double ActualProgress { get; set; } } 

and I wrote this query:

  TaskWeekUI ti = tis.First( t => t.PlanProgress > 0 && t.EndDate == tis.Where(p => p.PlanProgress != null && p.PlanProgress > 0).Max(w => w.EndDate)); 

Is this query true? Can I write my request better than this?

+6
c # max linq where
source share
3 answers

I think you need one for which PlanProgress > 0 has the most recent EndDate .

 TaskWeekUI ti = tis.Where(t => t.PlanProgress > 0) .OrderByDescending(t => t.EndDate) .FirstOrDefault(); 
+26
source share

This query seems correct in terms of the result.

But in your inner query, tis.Where(p => p.PlanProgress != null && p.PlanProgress > 0).Max(w => w.EndDate) calculated for each item in the collection using t.PlanProgress > 0

Thus, this is the best way to get the Max value outside the query as follows:

 var max = tis.Where(p => p.PlanProgress != null && p.PlanProgress > 0).Max(w => w.EndDate); tis.First( t => t.PlanProgress > 0 && t.EndDate == max); 

Go ahead p.PlanProgress! = Null is always true, since p.PlanProgress is not Nullable. So, our code is as follows:

 var max = tis.Where(p => p.PlanProgress > 0).Max(w => w.EndDate); tis.First( t => t.PlanProgress > 0 && t.EndDate == max); 

Or you can change the definition of your class and make p.PlanProgress of type Nullable:

 public class TaskWeekUI { public Guid TaskWeekId { get; set; } public Guid TaskId { get; set; } public Guid WeekId { get; set; } public DateTime EndDate { get; set; } public string PersianEndDate { get; set; } public double? PlanProgress { get; set; } public double ActualProgress { get; set; } } var max = tis.Where(p => p.PlanProgress.HasValue && p.PlanProgress.Value > 0).Max(w => w.EndDate); tis.First( t => t.PlanProgress.HasValue && t.PlanProgress.Value > 0 && t.EndDate == max); 
+3
source share

You do not need to compare PlanProgress with null, because double is a structure type, it cannot be null.

If you want TaskWeekUI with Max EndDate and positive PlanProgress, you can try this code:

 TaskWeekUI ti = tis.Where(t => t.PlanProgress > 0).Max(w => w.EndDate); 
-one
source share

All Articles