How to Sort a list by field

33,142

Solution 1

You can use List.Sort

l.Sort((p, q) => p.Category.CompareTo(q.Category));

The advantage over the LINQ OrderBy is that you'll order the list in-place instead of generating an IOrderedEnumerable<T> that then you have to re-transform in a List<T>.

Solution 2

Check out the LINQ OrderBy extension method.

MyList.OrderBy (p => p.Category);

If you need a more complex way to sort the categories, you could create a class which implements the IComparer interface, and implement your sort logic in it.

        public class SmartphonesFirst : IComparer<Product>
        {
            const string Smartphone = "Smartphone";

            public int Compare( Product x, Product y )
            {
                if( x.Category == Smartphone && y.Category != Smartphone )
                {
                    return -1;
                }
                if( y.Category == Smartphone && x.Category != Smartphone )
                {
                    return 1;
                }
                else
                {
                    return Comparer<String>.Default.Compare (x.Category, y.Category);
                }
            }
        }

You can do it without using LINQ:

            var l = new List<Product> ();
            l.Add (new Product ()
            {
                Name = "Omnia 7",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "Mercedes",
                Category = "Car"
            });

            l.Add (new Product ()
            {
                Name = "HTC",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "AMD",
                Category = "CPU"
            });

            l.Sort (new SmartphonesFirst ());

            foreach( var p in l )
            {
                Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
            }

Or, with using LINQ:

            var l = new List<Product> ();
            l.Add (new Product ()
            {
                Name = "Omnia 7",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "Mercedes",
                Category = "Car"
            });

            l.Add (new Product ()
            {
                Name = "HTC",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "AMD",
                Category = "CPU"
            });

            var sorted = l.OrderBy (p => p, new SmartphonesFirst ());

            foreach ( var p in sorted )
            {
                Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
            }

Solution 3

You can use the Sort method and a custom comparison, to sort by category (descending) and then by product (ascending):

MyList.Sort((a, b) => {
  // compare b to a to get descending order
  int result = b.Category.CompareTo(a.Category);
  if (result == 0) {
    // if categories are the same, sort by product
    result = a.Product.CompareTo(b.Product);
  }
  return result;
});

If you want to single out smartphones, and then sort ascending:

MyList.Sort((a, b) => {
  int result = (a.Category == "SmartPhone" ? 0 : 1) - (b.Category == "SmartPhone" ? 0 : 1);
  if (result == 0) {
    result = a.Category.CompareTo(b.Category);
    if (result == 0) {
      result = a.Product.CompareTo(b.Product);
    }
  }
  return result;
});
Share:
33,142
AshOoO
Author by

AshOoO

Updated on October 24, 2020

Comments

  • AshOoO
    AshOoO over 3 years

    Good day 4 u all

    I have a list of objects

    My objects like

    Product = "iPhone"; 
    Category = "SmartPhone";
    
    Product = "HP"; 
    Category = "PC";
    
    Product = "HTC"; 
    Category = "SmartPhone";
    

    And I insert each object into my test so its like

    List<Myobject> MyList = new List<Myobject>();
    

    And now I need to sord/order MyList by the category

    As I need my list to show the SmartPhone category first then other

  • Alex Essilfie
    Alex Essilfie over 12 years
    +1. for going a step further to sort on the product field when the category field is equal.
  • Frederik Gheysels
    Frederik Gheysels over 12 years
    IMHO, that's rather an disadvantage, since I see the 'ordered list' as a view on the original data. So, I prefer to let the original list 'untouched'.
  • xanatos
    xanatos over 12 years
    @FrederikGheysels Luckily then you can choose :-)