Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort a list by field

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

like image 280
AshOoO Avatar asked Oct 24 '11 09:10

AshOoO


People also ask

How do I sort a list in Java?

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

How do you sort a list by key?

sort() Syntax The syntax of the sort() method is: list.sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.

How do you sort a list in an array?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.


2 Answers

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>.

like image 66
xanatos Avatar answered Oct 22 '22 22:10

xanatos


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));
            }
like image 24
Frederik Gheysels Avatar answered Oct 22 '22 21:10

Frederik Gheysels