List<T> OrderBy Alphabetical Order

C#GenericsListLambdaSorting

C# Problem Overview


I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

C# Solutions


Solution 1 - C#

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

Solution 2 - C#

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

Solution 3 - C#

people.OrderBy(person => person.lastname).ToList();

Solution 4 - C#

you can use linq :) using :

System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();

Solution 5 - C#

private void SortGridGenerico< T >(
          ref List< T > lista		
	, SortDirection sort
	, string propriedadeAOrdenar)
{

	if (!string.IsNullOrEmpty(propriedadeAOrdenar)
	&& lista != null
	&& lista.Count > 0)
	{

		Type t = lista[0].GetType();

		if (sort == SortDirection.Ascending)
		{

			lista = lista.OrderBy(
				a => t.InvokeMember(
					propriedadeAOrdenar
					, System.Reflection.BindingFlags.GetProperty
					, null
					, a
					, null
				)
			).ToList();
		}
		else
		{
			lista = lista.OrderByDescending(
				a => t.InvokeMember(
					propriedadeAOrdenar
					, System.Reflection.BindingFlags.GetProperty
					, null
					, a
					, null
				)
			).ToList();
		}
	}
}

Solution 6 - C#

for me this useful dummy guide - Sorting in Generic List - worked. it helps you to understand 4 ways(overloads) to do this job with very complete and clear explanations and simple examples

  • List.Sort ()
  • List.Sort (Generic Comparison)
  • List.Sort (Generic IComparer)
  • List.Sort (Int32, Int32, Generic IComparer)

Solution 7 - C#

You can use this code snippet:

var New1 = EmpList.OrderBy(z => z.Age).ToList();

where New1 is a List<Employee>.

EmpList is variable of a List<Employee>.

z is a variable of Employee type.

Solution 8 - C#

You can also use

model.People = model.People.OrderBy(x => x.Name).ToList();

Solution 9 - C#

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaaS DeveloperView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#DanimalView Answer on Stackoverflow
Solution 4 - C#vampire203View Answer on Stackoverflow
Solution 5 - C#BrunoView Answer on Stackoverflow
Solution 6 - C#ImanView Answer on Stackoverflow
Solution 7 - C#AnshuMan SrivAstavView Answer on Stackoverflow
Solution 8 - C#rosselder83View Answer on Stackoverflow
Solution 9 - C#howserssView Answer on Stackoverflow