Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - C# - Using lambda - Get a set of data from a Collection

Tags:

c#

linq

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?

like image 210
Harsha Avatar asked Nov 15 '12 07:11

Harsha


1 Answers

You can use Max and Min for this:

double minDouble = obsColl.Min(item => ConvertToDouble(item.X));
double maxDouble = obsColl.Max(item => ConvertToDouble(item.X));
like image 134
McGarnagle Avatar answered Nov 15 '22 00:11

McGarnagle