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
If you mean an in-place sort (i.e. the list is updated):
ReplyDeletepeople.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
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:
ReplyDeletevar 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...)
people.OrderBy(person => person.lastname).ToList();
ReplyDeleteyou can use linq :) using :
ReplyDeleteSystem.linq;
var newList = people.OrderBy(x=>x.Name).ToList();
private void SortGridGenerico< T >(
ReplyDeleteref 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();
}
}
}
for me this useful dummy guide works
ReplyDeleteSorting_in_Generic_List