Lista Uporządkowana Według Kolejności Alfabetycznej

Używam C# na frameworku 3.5. Szukam szybkiego sortowania generycznego List<T>. Dla przykładu, załóżmy, że mam listę typu Person z właściwością lastname. Jak posortować tę listę używając wyrażenia lambda?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)
Author: Ahmed Abdelhameed, 2008-10-09

9 answers

Jeśli masz na myśli sortowanie w miejscu (tzn. lista jest aktualizowana):

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

Jeśli masz na myśli nową listę:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
 625
Author: Marc Gravell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-09 16:49:55

Czy trzeba posortować listę na miejscu, czy po prostu uporządkować jej zawartość? To drugie jest łatwiejsze:

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

Aby sortować w miejscu, potrzebujesz IComparer<Person> lub Comparison<Person>. W tym celu warto rozważyć ProjectionComparer w MiscUtil.

(wiem, że ciągle wspominam MiscUtil - to po prostu jest aktualne...)

 90
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-09 16:49:50
people.OrderBy(person => person.lastname).ToList();
 22
Author: Danimal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-22 08:36:30

Możesz użyć linq :) używając :

System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();
 21
Author: vampire203,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-28 22:08:30
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();
        }
    }
}
 11
Author: Bruno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-22 09:22:43

Dla mnie ten przydatny poradnik - sortowanie w Generic List- zadziałał. pomaga zrozumieć 4 sposoby(przeciążenia), aby wykonać tę pracę dzięki bardzo kompletnym i jasnym wyjaśnieniom i prostym przykładom

  • Lista.Sort ()
  • Lista.Sort (Generic Comparison)
  • Lista.Sort (Generic IComparer)
  • Lista.Sort (Int32, Int32, Generic IComparer)
 4
Author: Iman Abidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-16 11:47:36

Możesz użyć tego fragmentu kodu:

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

Gdzie New1 jest List<Employee>.

EmpList jest zmienną List<Employee>.

z jest zmienną typu Employee.

 4
Author: AnshuMan SrivAstav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-19 21:32:49

Możesz również użyć

model.People = model.People.OrderBy(x => x.Name).ToList();
 4
Author: rosselder83,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-02 08:59:43

Jest to Rodzajowy sorter. Wywołane przełącznikiem poniżej.

Dvm.PagePermissions jest właściwością na moim ViewModel typu Lista T w tym przypadku t jest klasą modelu EF6 o nazwie page_permission.

Dvm.UserNameSortDir jest właściwością typu string na viewmodel, która utrzymuje następny kierunek sortowania. Ten, który jest używany w widoku.

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;
    }
 1
Author: howserss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-19 21:33:41