14 October 2013

How do I – Sort a list of custom class objects in descending order in C#?

Suppose we have a custom class defined thus:

class CustomClass
    {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public string String3 { get; set; }
        public int Int1 { get; set; }
        public int Int2 { get; set; }

        public CustomClass()
        {
            String1 = "";
            String2 = "";
            String3 = "";
            Int1 = 0;
            Int2 = 0;
        }

        public int Calculate()
        {
            return Int1 + Int2;
        }
    }

As we can see, the class initializes it’s variables and has a Calculate() method that simply returns the added value of the two int variables of the class. Now suppose we have a list of these class objects in our app with varying values thus:

 CustomClass MyClass = new CustomClass();
    MyClass.Int1 = 10;
    MyClass.Int2 = 5;
    CustomClass My2ndClass = new CustomClass();
    My2ndClass.Int1 = 7;
    CustomClass My3rdClass = new CustomClass();

    List lst = new List();
    lst.Add(My2ndClass); 
    lst.Add(MyClass);
    lst.Add(My3rdClass);
We now have a list containing 3 of our custom class objects. The first object in the list has an Int1 value of 10. The second has an Int1 value of 5 and the third, given the class’ initialization method, will have an Int1 value of 0. Given the order that we added the class objects to our list, the list, when looking at the Int1 field would look thus: 7, 10, 0 How do we go about sorting this list by any one of the variable fields of the custom class, say Int1 in our case? The built in support for Linq in Visual C# and the .NET Framework, actually makes this very easy. Using a Lambda expression, the task becomes a one liner thus:
 lst = lst.OrderByDescending(x => x.Int1).ToList();
We start with the OrderByDescending() method and then pass the Lambda expression to reference back to the object itself. The x => part of the expression tells C# to reference back to the calling object which in our case is lst. C# will reference back to lst as x which is where the x.Int1 then instructs the OrderByDescending method to use the Int1 field as the value by which to sort, in descending order, the x object which translates to lst. By appending the ToList() method to the back of the statement, C# will take the sorted result and generate a new List<> object which we simply assign back to the original lst variable. If we needed to sort in ascending order we would use the OrderBy() method instead thus making the statement:
 lst = lst.OrderBy(x => x.Int1).ToList();
Cheers C

No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...