CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2009
    Location
    Stuttgart, Germany
    Posts
    56

    Get the Maximum Value from a List

    Well guys, I have variable-sized List and I have populated it with double values...

    List<double> tempAvg = new List<double>();

    I want to know the Maximum value within the List. I thought first to sort the List and then get the last index, but I dont know how to do that.

    any Idea?

  2. #2
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Get the Maximum Value from a List

    There is Array.Sort() method, if you are using fx3.5 with LINQ, you can use Max() extension method directly.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  3. #3
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Get the Maximum Value from a List

    Use the Sort method that built into the List. You will have to do a custom sor to get the list in the descending order, something like this
    Code:
                List<double> tempAvg = new List<double>();
                tempAvg.Add(12.90);
                tempAvg.Add(2.90);
                tempAvg.Add(13.90);
                tempAvg.Add(1.90);
                tempAvg.Sort(delegate(double d1, double d2) 
                {
                    return d2.CompareTo(d1);
                });
                Console.WriteLine(tempAvg[0].ToString());

  4. #4
    Join Date
    Mar 2009
    Location
    Stuttgart, Germany
    Posts
    56

    Re: Get the Maximum Value from a List

    Thank you very much, it was very helpful.

  5. #5
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Get the Maximum Value from a List

    Quote Originally Posted by boudino View Post
    There is Array.Sort() method, if you are using fx3.5 with LINQ, you can use Max() extension method directly.
    I just tried the extension method in 3.5 and it works like a charm. Thanks
    Code:
    //top of the module
    using System.Linq;
    
    //all other code
                List<double> tempAvg = new List<double>();
                tempAvg.Add(12.90);
                tempAvg.Add(2.90);
                tempAvg.Add(13.90);
                tempAvg.Add(1.90);
                Console.WriteLine(tempAvg.Max().ToString());

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured