Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. I Don't Understand How To Sort A Generic List of Objects [modified]

I Don't Understand How To Sort A Generic List of Objects [modified]

Scheduled Pinned Locked Moved C#
helptutorialtestingbeta-testingquestion
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    That Asian Guy
    wrote on last edited by
    #1

    Just for testing I found this random class in an example file.

    public class Product
    {
    public Product(string name, int quantityInStock)
    {
    _name = name;
    _quantityInStock = quantityInStock;
    }
    private string _name;
    public string Name
    {
    get { return _name; }
    set { _name = value; }
    }
    private int _quantityInStock;
    public int QuantityInStock
    {
    get { return _quantityInStock; }
    set { _quantityInStock = value; }
    }
    }

    Now, I created a list.

    List<Product> products = new List<Product>();

    And added some objects.

    products.Add(new Product("A", 5));
    products.Add(new Product("B", 4));
    products.Add(new Product("C", 3));
    products.Add(new Product("D", 2));
    products.Add(new Product("E", 1));

    However, when I tried using products.Sort(), I got an error. This did not surprise me since I didn't expect it to sort properly. However, I saw the other two overloads List<products>.Sort(Comparison<Product> comparison) and List<products>.Sort(IComparer<Product> comparer). I read the MSDN pages but still don't understand how to use these. Can someone provide some help? Thanks in advance. P.S. The casing is messed up in the post but don't worry about it :laugh:

    modified on Sunday, October 5, 2008 5:27 PM

    L realJSOPR G 3 Replies Last reply
    0
    • T That Asian Guy

      Just for testing I found this random class in an example file.

      public class Product
      {
      public Product(string name, int quantityInStock)
      {
      _name = name;
      _quantityInStock = quantityInStock;
      }
      private string _name;
      public string Name
      {
      get { return _name; }
      set { _name = value; }
      }
      private int _quantityInStock;
      public int QuantityInStock
      {
      get { return _quantityInStock; }
      set { _quantityInStock = value; }
      }
      }

      Now, I created a list.

      List<Product> products = new List<Product>();

      And added some objects.

      products.Add(new Product("A", 5));
      products.Add(new Product("B", 4));
      products.Add(new Product("C", 3));
      products.Add(new Product("D", 2));
      products.Add(new Product("E", 1));

      However, when I tried using products.Sort(), I got an error. This did not surprise me since I didn't expect it to sort properly. However, I saw the other two overloads List<products>.Sort(Comparison<Product> comparison) and List<products>.Sort(IComparer<Product> comparer). I read the MSDN pages but still don't understand how to use these. Can someone provide some help? Thanks in advance. P.S. The casing is messed up in the post but don't worry about it :laugh:

      modified on Sunday, October 5, 2008 5:27 PM

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You need to provide your own comparison method for your product class which lets you compare two products in the way you want to. Here's an example:

      private static int CompareProducts(Product x, Product y)
      {
      if (x == null)
      {
      if (y == null)
      {
      // If x is null and y is null, they're equal.
      return 0;
      }
      else
      {
      // If x is null and y is not null, y is greater.
      return -1;
      }
      }
      else
      {
      // If x is not null...
      if (y == null) // ...and y is null, x is greater.
      {
      return 1;
      }
      else
      {
      // ...and y is not null, compare by whatever you want :-)
      // here we compare either by name if different, otherwise by quantity in stock
      if(x.Name == y.Name)
      return x.QuantityInStock.CompareTo(y.QuantityInStock);
      else
      return x.Name.CompareTo(y.Name);
      }
      }

      }

      and then sort them:

      producs.Sort(CompareProducts);

      regards

      T 1 Reply Last reply
      0
      • L Lost User

        You need to provide your own comparison method for your product class which lets you compare two products in the way you want to. Here's an example:

        private static int CompareProducts(Product x, Product y)
        {
        if (x == null)
        {
        if (y == null)
        {
        // If x is null and y is null, they're equal.
        return 0;
        }
        else
        {
        // If x is null and y is not null, y is greater.
        return -1;
        }
        }
        else
        {
        // If x is not null...
        if (y == null) // ...and y is null, x is greater.
        {
        return 1;
        }
        else
        {
        // ...and y is not null, compare by whatever you want :-)
        // here we compare either by name if different, otherwise by quantity in stock
        if(x.Name == y.Name)
        return x.QuantityInStock.CompareTo(y.QuantityInStock);
        else
        return x.Name.CompareTo(y.Name);
        }
        }

        }

        and then sort them:

        producs.Sort(CompareProducts);

        regards

        T Offline
        T Offline
        That Asian Guy
        wrote on last edited by
        #3

        Thanks, so return 1 means the first is greater, return 0 means they're the same, and return -1 means the second is greater?

        L 1 Reply Last reply
        0
        • T That Asian Guy

          Just for testing I found this random class in an example file.

          public class Product
          {
          public Product(string name, int quantityInStock)
          {
          _name = name;
          _quantityInStock = quantityInStock;
          }
          private string _name;
          public string Name
          {
          get { return _name; }
          set { _name = value; }
          }
          private int _quantityInStock;
          public int QuantityInStock
          {
          get { return _quantityInStock; }
          set { _quantityInStock = value; }
          }
          }

          Now, I created a list.

          List<Product> products = new List<Product>();

          And added some objects.

          products.Add(new Product("A", 5));
          products.Add(new Product("B", 4));
          products.Add(new Product("C", 3));
          products.Add(new Product("D", 2));
          products.Add(new Product("E", 1));

          However, when I tried using products.Sort(), I got an error. This did not surprise me since I didn't expect it to sort properly. However, I saw the other two overloads List<products>.Sort(Comparison<Product> comparison) and List<products>.Sort(IComparer<Product> comparer). I read the MSDN pages but still don't understand how to use these. Can someone provide some help? Thanks in advance. P.S. The casing is messed up in the post but don't worry about it :laugh:

          modified on Sunday, October 5, 2008 5:27 PM

          realJSOPR Offline
          realJSOPR Offline
          realJSOP
          wrote on last edited by
          #4

          Go here. The example is simple enough to understand. http://dotnetslackers.com/Community/blogs/simoneb/archive/2007/06/20/How-to-sort-a-generic-List_3C00_T_3E00_.aspx[^]

          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

          1 Reply Last reply
          0
          • T That Asian Guy

            Just for testing I found this random class in an example file.

            public class Product
            {
            public Product(string name, int quantityInStock)
            {
            _name = name;
            _quantityInStock = quantityInStock;
            }
            private string _name;
            public string Name
            {
            get { return _name; }
            set { _name = value; }
            }
            private int _quantityInStock;
            public int QuantityInStock
            {
            get { return _quantityInStock; }
            set { _quantityInStock = value; }
            }
            }

            Now, I created a list.

            List<Product> products = new List<Product>();

            And added some objects.

            products.Add(new Product("A", 5));
            products.Add(new Product("B", 4));
            products.Add(new Product("C", 3));
            products.Add(new Product("D", 2));
            products.Add(new Product("E", 1));

            However, when I tried using products.Sort(), I got an error. This did not surprise me since I didn't expect it to sort properly. However, I saw the other two overloads List<products>.Sort(Comparison<Product> comparison) and List<products>.Sort(IComparer<Product> comparer). I read the MSDN pages but still don't understand how to use these. Can someone provide some help? Thanks in advance. P.S. The casing is messed up in the post but don't worry about it :laugh:

            modified on Sunday, October 5, 2008 5:27 PM

            G Offline
            G Offline
            Guffa
            wrote on last edited by
            #5

            If you for example want to sort by product name, you provide a comparison that compares that property for two items: products.Sort(delegate(Product x, Product y){return string.Compare(x.Name,y.Name);}); Or if you use framework 3.5, you can use a lambda expression: products.Sort((x, y) => string.Compare(x.Name,y.Name));

            Despite everything, the person most likely to be fooling you next is yourself.

            realJSOPR 1 Reply Last reply
            0
            • T That Asian Guy

              Thanks, so return 1 means the first is greater, return 0 means they're the same, and return -1 means the second is greater?

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              That's correct.

              1 Reply Last reply
              0
              • G Guffa

                If you for example want to sort by product name, you provide a comparison that compares that property for two items: products.Sort(delegate(Product x, Product y){return string.Compare(x.Name,y.Name);}); Or if you use framework 3.5, you can use a lambda expression: products.Sort((x, y) => string.Compare(x.Name,y.Name));

                Despite everything, the person most likely to be fooling you next is yourself.

                realJSOPR Offline
                realJSOPR Offline
                realJSOP
                wrote on last edited by
                #7

                I tried both of those, and it looks like you can only do string comparisons that way. How do you do int, double, etc. without using ToString()?

                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                L G 2 Replies Last reply
                0
                • realJSOPR realJSOP

                  I tried both of those, and it looks like you can only do string comparisons that way. How do you do int, double, etc. without using ToString()?

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  L Offline
                  L Offline
                  leppie
                  wrote on last edited by
                  #8

                  John Simmons / outlaw programmer wrote:

                  How do you do int, double, etc. without using ToString()?

                  Like normal...

                  list.Sort( (x,y) => x.Int.CompareTo(y.Int))

                  xacc.ide - now with TabsToSpaces support
                  IronScheme - 1.0 alpha 4a out now (29 May 2008)
                  ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                  1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    I tried both of those, and it looks like you can only do string comparisons that way. How do you do int, double, etc. without using ToString()?

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    G Offline
                    G Offline
                    Guffa
                    wrote on last edited by
                    #9

                    For integer values you can just subtract them: products.Sort(delegate(Product x, Product y){return x.QuantityInStock - y.QuantityInStock;}); For double values you can use the Math.Sign method to get a suitable integer value from the difference: products.Sort(delegate(Product x, Product y){return Math.Sign(x.Price - y.Price);});

                    Despite everything, the person most likely to be fooling you next is yourself.

                    realJSOPR 1 Reply Last reply
                    0
                    • G Guffa

                      For integer values you can just subtract them: products.Sort(delegate(Product x, Product y){return x.QuantityInStock - y.QuantityInStock;}); For double values you can use the Math.Sign method to get a suitable integer value from the difference: products.Sort(delegate(Product x, Product y){return Math.Sign(x.Price - y.Price);});

                      Despite everything, the person most likely to be fooling you next is yourself.

                      realJSOPR Offline
                      realJSOPR Offline
                      realJSOP
                      wrote on last edited by
                      #10

                      After seeing that, I prefer to stick with the tried/true method of writing the various Comparison delegate functions. It's much easier to understand and maintain. When I code, I don't go "clever" nearly as often as I go "maintainable".

                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                      -----
                      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups