5

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?

4 Answers 4

4

You can use Max and Min for this:

double minDouble = obsColl.Min(item => ConvertToDouble(item.X));
double maxDouble = obsColl.Max(item => ConvertToDouble(item.X));
2
  • Would this cause an internal iteration on the entire collection? What I mean is if I run the Min once and the max once, is it an O(n) performance twice?
    – Mechanik
    Nov 15, 2012 at 8:53
  • @Harsha yes, that's my understanding -- it will iterate over the whole collection (although for all I know there may be some kind of optimization built in). The Linq methods like Max and Min are extension methods of IEnumerable, so at their core you can assume they're simply performing an iteration.
    – McGarnagle
    Nov 15, 2012 at 9:09
3

you can go over this examples 101 LINQ Samples

1
  • 1
    +1 Finally, someone else who wants the people to help themselves with the right material. :o)
    – DHN
    Nov 15, 2012 at 7:48
2

It is more efficient

    double minDouble =ConvertToDouble( obsColl.Min(item => item.X));
    double maxDouble = ConvertToDouble(obsColl.Max(item => item.X));
0

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

1
  • That being said the internal algorithm probably uses two loops where in your foreach you can manage just one. If performance is an issue for you profile the two solutions and pick the better one. Nov 15, 2012 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.