In-place and out-of-place list sorting in C#

You may need to sort C# list elements in-place sometimes or copy elements of a list to another list according to some sort order (which is in fact another way to sort list elements). Linq provides an easy way to achieve both purposes. Let’s say you have a Project entity with FirstName property.

In-place Sorting: Use Sort function to update elements of a collection according to sort order.

        (x, y) => string.Compare(x.FirstName, y.FirstName));

// sort by DateCreated
        (x,y) => DateTime.Compare(y.DateCreated, x.DateCreated));

Out-of-order Sorting: Use OrderBy function to copy elements from a list to another according to some custom field order.

var orderedProjects = this.Projects.OrderBy(x => x.FirstName)