Reputation: 679
I have a struct TimePoint which is similar to a Point except, the x value is a datetime, an observable collection of these timepoints and a method that takes a datetime and returns a double value.
I want to retrieve the max and min value of the doubles that are returned from the datetimes in this collection.
I am new to linq and am unable to figure out the query I would have to pass on the observable collection to achieve this.
Here's what I am trying to get:
double minDouble = 0;
double maxDouble = 0;
foreach(TimePoint item in obsColl)
{
var doubleVal = ConvertToDouble(item.X); //Here x is a datetime
if(minDouble > doubleVal)
minDouble = doubleVal;
if(maxDouble < doubleVal)
maxDouble = doubleVal;
}
How can I achieve this using LINQ? Or is LINQ not ideal for this?
Upvotes: 5
Views: 326
Reputation: 32182
Using the fluent assertion package
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
public void MyTestMethod()
{
var list = new List<double>() { 1, 3, 5, 2, 9, 4 };
var minmax = from l in list
group l by 1 into g
select new
{
min = g.Min(),
max = g.Max()
};
minmax.First().min.Should().Be(1);
minmax.First().max.Should().Be(9);
}
Now the group l by 1 into g is a hack because linq will not allow aggregates without groups but it is not too bad
Upvotes: 0
Reputation: 1720
It is more efficient
double minDouble =ConvertToDouble( obsColl.Min(item => item.X));
double maxDouble = ConvertToDouble(obsColl.Max(item => item.X));
Upvotes: 2
Reputation: 102753
You can use Max
and Min
for this:
double minDouble = obsColl.Min(item => ConvertToDouble(item.X));
double maxDouble = obsColl.Max(item => ConvertToDouble(item.X));
Upvotes: 4