locked
list<Double> sorting desc RRS feed

  • Question

  • hello

     I have a list<> of double variable

     

     List<Double> dinosaurs = new List<Double>();
                dinosaurs.Add(-2.102);
                dinosaurs.Add(1.20);
                dinosaurs.Add(72.32);
                dinosaurs.Add(-1.3);
                dinosaurs.Add(2.33);

    i want to sort it accending and desending

     

    how to do this


    It's Me
    Thursday, May 27, 2010 8:09 AM

Answers

  • List<Double> dinosaurs = new List<Double>();
       dinosaurs.Add(-2.102);
       dinosaurs.Add(1.20);
       dinosaurs.Add(72.32);
       dinosaurs.Add(-1.3);
    
       dinosaurs.Add(2.33);
       Console.WriteLine("Unsorted:");
       foreach (var x in dinosaurs)
        Console.WriteLine(x);
       var sorted = from dbl in dinosaurs
         orderby dbl descending
         select dbl;
       Console.WriteLine("Sorted:");
       foreach (var x in sorted.ToList())
        Console.WriteLine(x);
    
       Console.ReadLine();
    Likewise you'll get ascending too...
    I am a bundle of mistakes intertwined together with good intentions
    • Proposed as answer by A.m.a.L Hashim Thursday, May 27, 2010 8:29 AM
    • Marked as answer by It_s Meee Thursday, May 27, 2010 9:11 AM
    Thursday, May 27, 2010 8:23 AM

All replies

  • List<Double> dinosaurs = new List<Double>();
       dinosaurs.Add(-2.102);
       dinosaurs.Add(1.20);
       dinosaurs.Add(72.32);
       dinosaurs.Add(-1.3);
    
       dinosaurs.Add(2.33);
       Console.WriteLine("Unsorted:");
       foreach (var x in dinosaurs)
        Console.WriteLine(x);
       var sorted = from dbl in dinosaurs
         orderby dbl descending
         select dbl;
       Console.WriteLine("Sorted:");
       foreach (var x in sorted.ToList())
        Console.WriteLine(x);
    
       Console.ReadLine();
    Likewise you'll get ascending too...
    I am a bundle of mistakes intertwined together with good intentions
    • Proposed as answer by A.m.a.L Hashim Thursday, May 27, 2010 8:29 AM
    • Marked as answer by It_s Meee Thursday, May 27, 2010 9:11 AM
    Thursday, May 27, 2010 8:23 AM
  • you can code like this-

    List<Double> dinosaurs = new List<Double>();
                    dinosaurs.Add(-2.102);
                    dinosaurs.Add(1.20);
                    dinosaurs.Add(72.32);
                    dinosaurs.Add(-1.3);
                    dinosaurs.Add(2.33);
                    dinosaurs.Sort(); //for asscending sorting
                    dinosaurs.Reverse();//for descending sorting

     

    regards

    jayant

    Thursday, May 27, 2010 8:34 AM
  • dinosaurs.Sort(); I reckon if that doesn't work a peek onto a sorter I have suggests

     dinosaurs.Sort(Compare);

    int Compare(double x, double y)

    {

         return (x < y) ? -1 : (x > y) ? 1 : 0;

    }

    or simular, which does look far to basic not to be grasped by the basic sort routine.

    see help on List<>.Sort(...)

     

     

    Thursday, May 27, 2010 8:41 AM
  • From the same place where you got the example you find also the sorting behaviour.

    Also I suggest you could study the IComparable interface, the sort ovveridable default method, the LINQ syntax.

    Giuseppe

    Thursday, May 27, 2010 8:57 AM
  • That linq is going to be pretty slow compared to doing directly using Sort(). You should use dinosaurs.Sort() to sort it ascending (just like in the sample code you got your Dinosaurs example from).

    To sort it in descending order, you should use this:

    dinosaurs.Sort((x,y)=>(y.CompareTo(x)));

    Alternatively you can do this:

    dinosaurs.Sort((x,y)=>(Comparer<double>.Default.Compare(y,x)));

    (I prefer the first though ;)

    Thursday, May 27, 2010 9:19 AM
  • he, nice lambda expressions, since I never used it I had a little test combining things

      private class SortTst
      {
       public SortTst()
       {
        List<Double> dinosaurs = new List<Double>();
        dinosaurs.Add(-2.102);
        dinosaurs.Add(1.20);
        dinosaurs.Add(72.32);
        dinosaurs.Add(-1.3);
        dinosaurs.Add(2.33);
        string s = "unsorted: ";
        foreach (Double dlb in dinosaurs)
         s += dlb.ToString() + " ";
        dinosaurs.Sort((x, y) => ((x < y) ? -1 : (x > y) ? 1 : 0)); //for ascending sorting
        s += "\r\n sorted: ";
        foreach (Double dlb in dinosaurs)
         s += dlb.ToString() + " ";
        dinosaurs.Sort((y, x) => ((x < y) ? -1 : (x > y) ? 1 : 0)); //for descending sorting
        s += "\r\nreversed: ";
        foreach (Double dlb in dinosaurs)
         s += dlb.ToString() + " ";
        MessageBox.Show(s);
       }
      }
    
     

    which works far better then this forum (hi hi) (first enter text, than add code using the html button it seems, escaping from it (???) )

    the RHS of the lambda's works for all (numerical) types and I reckon all classes that implement the comparison operators, and I reckon captured by CompareTo methods.

    Funny, tried to do this with a Collection<Double>, however Collection<T> doesn't seem to implement the Sort() method.

    (at least Framework 3.5, VS 2010 hasn't arrived yet)

     

    Thursday, May 27, 2010 11:43 AM
  • Note that you can simplify:

    dinosaurs.Sort((x, y) => ((x < y) ? -1 : (x > y) ? 1 : 0))

    to:

    dinosaurs.Sort((x,y) => Math.Sign(x-y));

    [EDIT] Fixed, as described by Wyck below.

    Thursday, May 27, 2010 12:05 PM
  • Note that you can simplify:

    dinosaurs.Sort((x, y) => ((x < y) ? -1 : (x > y) ? 1 : 0))

    to:

    dinosaurs.Sort(Math.Sign(x-y));

     

    I don't think so.  You need at least this:

    dinosaurs.Sort((x,y) => Math.Sign(x-y));

    Thursday, May 27, 2010 1:51 PM
  • Note that you can simplify:

    dinosaurs.Sort((x, y) => ((x < y) ? -1 : (x > y) ? 1 : 0))

    to:

    dinosaurs.Sort(Math.Sign(x-y));

     

    I don't think so.  You need at least this:

    dinosaurs.Sort((x,y) => Math.Sign(x-y));

    Good point - I typed it in wrong; I was focussing on the ternary stuff.

    (I'll go edit my reply to fix it now).

    Thursday, May 27, 2010 2:19 PM
  • I know this was answered, but I just read this today. Take a look at the sort extension method.

     

    http://www.codeproject.com/KB/aspnet/Entity_Collection.aspx

     

    Thursday, May 27, 2010 3:24 PM
  • Just a minor point, Math.Sign(..) shows there are many ways to skin this cat, as usual.

    Math.Sign might indeed be a simplyfication for the basic numeric types, (don't know wheter this works also on say BigInteger)

    my ternary expression works (in my experience) for all data whereupon an ordering and corresponding operators ('<' and '>') are defined, I can see myself using it on some of my own classes, as I had to implement my own Integer class since Biginteger wasn't present when I started my MagicHypercubes project. Hypercubes also have an ordering defined (Math.Sign(..) definitely won't work here (hi hi)).

    The RHS simply depends on data used, and can take indeed many forms (no problem).

    Friday, May 28, 2010 5:16 AM
  • Just a minor point, Math.Sign(..) shows there are many ways to skin this cat, as usual.

    Math.Sign might indeed be a simplyfication for the basic numeric types, (don't know wheter this works also on say BigInteger)

    my ternary expression works (in my experience) for all data whereupon an ordering and corresponding operators ('<' and '>') are defined, I can see myself using it on some of my own classes, as I had to implement my own Integer class since Biginteger wasn't present when I started my MagicHypercubes project. Hypercubes also have an ordering defined (Math.Sign(..) definitely won't work here (hi hi)).

    The RHS simply depends on data used, and can take indeed many forms (no problem).

    If your goal is to make it as general purpose as possible (which it normally should be) then you should use

    dinosaurs.Sort((x,y)=>(y.CompareTo(x)));

    as I said in my first reply in this thread.

    The problem with using "<" and ">" is that they are not always defined for comparable types, but CompareTo() MUST always be defined for comparable types (since, by definition, a comparable type must implement IComparable, otherwise is is not comparable!).

    Friday, May 28, 2010 8:58 AM
  • Funny, the classes I wrote (back in FrameWork 2.0 days) show the operators '<' and '>' implemented. No sign (checked) that I needed to make my classes IComparable, nor recall that I needed to change toward it.

    No problem with either form of the RHS of that lambda expression, whatever works. The pasted sample was merely a test of the lambda expression. Simply have no real use for "Interfaces", probably the word is a misnomer, as I don't see what it is to "interface" with (but that is probably my misunderstanding of microsoft mumbo-jumbo (aka implemented overhead / missing c# features))

    Will have to look into "IComparable" and see whether it serves some purpose.

    Friday, May 28, 2010 11:09 AM
  • You'll find that IComparable<T> is actually quite important. :)

    For example, if you run the following code, you'll get this exception at run-time:

    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable.

    using System;
    using System.Collections.Generic;
    
    namespace Demo
    {
      class Program
      {
        static void Main()
        {
          List<MyClass> list = new List<MyClass> {new MyClass(), new MyClass()};
          list.Sort();
        }
      }
    
      class MyClass
      {
      }
    }
    

    If you're creating classes that overload operator<, operator> and operator==, you are supposed to implement them in terms of IComparable<T>.CompareTo() so that you can use all the .Net built-in stuff such as List.Sort().

    For example, if your class only overloads operator<, operator> and operator==, and you have a List<> of items of that type, then List<>.Sort() will fail if you haven't also defined a CompareTo().

    Friday, May 28, 2010 1:21 PM
  • From the help on List<T>.Sort() the default sorter is CompareTo, using this default the routine needs to be defined, no problem as it maps simply onto the ternary statement. Some chicken egg problem, which one you reckon to implement.

    I changed from ArrayList to Collection<T> which doesn't have Sort() for some reason.

    Because Sort() not needed thus far, simply didn't encounter the need to implement IComparable.

    As help on List<T> shows the darn classes need not be IComparable, it is suggested in order to use the BinarySearch and Sort methods. So the importance of IComparable is related to these two routines (possibly more). Suggest to me the reverse using the lambda statement makes adding IComparable superfluous, but that's merely a matter of testing which is more efficient and more such concernes.

    A matter of taste / commonly used (/best) practise. No problem with adding the corresponding code might I decide to reupload my more general classes, but probably BigInteger makes this a non-issue (save some extremely special routines relevant to MagicHyperCubes)

    Further libraries I don't have for public interest.

    Monday, May 31, 2010 11:16 AM
  • I don't believe it's actually a matter of taste whether you implement the comparison operators in terms of IComparable<T>.CompareTo(), but it's up to you how you write your own code, I guess.
    Monday, May 31, 2010 12:27 PM