ChatGPT解决这个技术问题 Extra ChatGPT

List<T> OrderBy Alphabetical Order

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(???? => ?????)

M
Marc Gravell

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

I believe that first one wants to be people.Sort((x, y) => string.Compare(x.LastName, y.LastName) < 0);
@James: I wouldn't think so. Comparison returns int, not bool.
I wonder if you want to OrderBy Firstname and Lastname... what should you write?
var newList = people.OrderBy(x=>x.FirstName).ThenBy(x=>x.LastName).ToList();
@Faraz (x,y)=>x.price.CompareTo(y.price)
J
Jon Skeet

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


This worked for me, but only after I appended ".ToList()": contemporariesOrderedByBirthYear = contemporaries.OrderBy(contemp => contemp.BirthYear).ToList();
@B.ClayShannon: Well you need that if you want a List<T>, but you don't need it if you just want to iterate.
S
Sparkup

you can use linq :) using :

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

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

Well, that still doesn't capture the result - you'd need a "List people = " on the left hand side...
This answer demonstates most common error when using LINQ - methods like OrderBy do not modify list, but rather return new "collection" (usually lazy IEnumerable<T>) that need to be assigned to something.
@AlexeiLevenkov how do you know this is the most common error when using LINQ?
b
bluish
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();
        }
    }
}

I
Iman

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)


Sort() is very useful especially when it's a List()
j
jalgames

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.


AnshuMan, there is nothing like a var type. New1 is List<Employee> and z is Employee.
r
rosselder83

You can also use

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

While this code sample may answer the question, it lacks explanation. As it stands now, it adds no value, and stands the change of being downvoted / deleted. Please add some explanation what is does and why it is a solution for the problem of the OP.
j
jalgames

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;
    }

I think that this is way too complicated. As you can see in the other answers, it can all be done in one single line (it doesn't necessarily mean that doing it in a single line is good, but I don't get the advantage of doing it like this)
This is for multi column sorting using AngularJS. It is essentially the single line sorting but it also sets the sort diretion variable. Its really not that complex if you look at it closely. I guess the Sort function is a little intimidating with all the generic stuff but if I took that definition out it is a 1 line Sort call.
Too complicated for what the Op requested. It is a good solution for a different problem though.