sort by name in csharp

To sort a list of objects in C# by their name, you can use either lambda expressions or LINQ.

Using Lambda Expression:

Suppose you have a list of objects of type Person with a Name property.

main.cs
List<Person> people = new List<Person>();
people.Add(new Person("John"));
people.Add(new Person("Alice"));
people.Add(new Person("Bob"));
138 chars
5 lines

Now, to sort the list by Name, you can use the following code:

main.cs
people = people.OrderBy(p => p.Name).ToList();
47 chars
2 lines

This will sort the 'people' list in ascending order by the Name property.

Using LINQ:

You can also use the LINQ extension method OrderBy to sort the list by Name.

main.cs
List<Person> sortedPeople = (from p in people
                             orderby p.Name
                             select p).ToList();
139 chars
4 lines

This will create a new list 'sortedPeople' and sort it in ascending order by the Name property.

Note: For both methods, the Person class should implement the IComparable interface and provide a CompareTo method to compare two Person objects by the Name property, in case you want to sort the list using the Sort method.

gistlibby LogSnag