Solved

List<> order alphabetically

Posted on 2009-07-16
2
239 Views
Last Modified: 2013-12-17
I want to order object in List<> alphabetically.
How do I order this list alphabetically according to FamilyName? The result should be (2,1,3)

List<User>uList=new List<User>;
User u1=new User;
u1.FirstName="John";
u1.FamilyName="Johnson";
uList.add(u1);
User u2=new User;
u2.FirstName="Howard";
u2.FamilyName="Anderson";
uList.add(u2);
User u3=new User;
u3.FirstName="Jim";
u3.FamilyName="Reagan";
uList.add(u3);
0
Comment
Question by:johnkainn
  • 2
2 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 24868435
You can use linq to sort a list of objects

var orderedList = uList
           .OrderBy(x => x.FamilyName) .ToList();
0
 
LVL 53

Accepted Solution

by:
Dhaest earned 250 total points
ID: 24868450
Another possibility:

The following code helps in sorting list of objects based on some propertys value.
Source: http://cherupally.blogspot.com/2009/04/how-to-sort-list-of-objects-in-c.html

Console.WriteLine(Sorted list, by name);
uList.Sort(delegate(Person p1, Person p2) { return p1.FamilyName.CompareTo(p2.FamilyName); });
uList.ForEach(delegate(User p) { Console.WriteLine(String.Format({0} {1}, p.FamilyName, p.FirstName)); });

Open in new window

0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

837 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question