Tuesday, June 5, 2012

C# List<> OrderBy Alphabetical Order


I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<>. For the sake of this example lets 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(???? => ?????)


Source: Tips4all

6 comments:

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

    ReplyDelete
  2. 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...)

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

    ReplyDelete
  4. you can use linq :) using :

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

    ReplyDelete
  5. 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();
    }
    }
    }

    ReplyDelete
  6. for me this useful dummy guide works

    Sorting_in_Generic_List

    ReplyDelete