Solved

List<> order alphabetically

Posted on 2009-07-16
2
236 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
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This video discusses moving either the default database or any database to a new volume.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now