I have a class TaskWeekUI 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 is true? Can I write my query better than this?
In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values.
Max () function in LINQ is used to return the maximum value from the collection. With the help of Max() function, it is easy to find the maximum value from a given data source using Max () function. In the other case, we have to write the code to get the maximum value from the list of values.
I think you want the one whose PlanProgress > 0
has a most recent EndDate
.
TaskWeekUI ti = tis.Where(t => t.PlanProgress > 0)
.OrderByDescending(t => t.EndDate)
.FirstOrDefault();
This query seems to be correct from point of view of result obtained.
But in your inner query tis.Where(p => p.PlanProgress != null && p.PlanProgress > 0).Max(w => w.EndDate)
is computed for each element in collection with t.PlanProgress > 0
So its a better way to obtain Max value outside of a 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);
Going further p.PlanProgress != null is allways true since p.PlanProgress is not of Nullable type. So our code becomes like this:
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 a definition of your class and make p.PlanProgress of Nullable type:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With