Solved

Sorting a List<> alphabetically

Posted on 2011-03-23
5
923 Views
Last Modified: 2013-12-17
Howdy Guys,

Hopefully quite an easy one for some easy points.

Im trying to sort a LIst<> alphabetically in WPF, Net 4.0.

Im just really confused what it is I type to make it sort alphabetically.

So far I have

  if (thisName != "")
            { //This creates a new contact 'c' when the Create Contact button on the form is pressed and adds it to the datalist.
               
               
                ContactDetails c = new ContactDetails();


               contactlist.Sort();

                foreach (ContactDetails c in contactlist)
                { 
                    c.Name.   <----- What the heck do I put here??
                    } 
                    

                //c.Name = thisName;
                c.Mobile = thisMobile;
                c.Secphone = thisSecphone;
                c.Email = thisEmail;
                c.Website = thisWebsite;
                c.Address = thisAddress;
                c.Notes = thisNotes;
                 contactlist.Add(c);
                 UpdatelistNames();

Open in new window


'c.Name' is then added to a listbox (updatelistnames) and its those names I want to appear alphabetically in the listbox.

Many Thanks

John
0
Comment
Question by:Bronco78th
5 Comments
 
LVL 7

Expert Comment

by:jdavistx
ID: 35202574
Do you want to sort a ListBox, or do you want to sort a List<ContactDetails> collection?

For the former, I believe you can simply set a Sorted value to "Alphabetically" on the ListBox control, and it will default to perform string comparison-based sorting as you add items to the ListBox.

For the latter, you can inherent the IComparable interface on your ContactDetails object
http://msdn.microsoft.com/en-us/library/system.icomparable.aspx

Then you can implement your own .CompareTo() method, which sorts the details based on string comparison of the Name property, and then you can call .Sort() on your collection to sort it.  The MSDN article has a good example.

There's several different ways you can achieve this sorting, and I believe there's a handful of Interfaces that allow for this kind of behavior (or equivalent), but I think IComparable is the way to go.  If you didn't want to implement that Interface, then you could use one of the various .Sort() method overloads
http://msdn.microsoft.com/en-us/library/3da4abas.aspx

Such as this:
http://msdn.microsoft.com/en-us/library/234b841s.aspx
Using this approach, you could create a class of sorters, such as ContactDetailSorters, and have several different methods that sort a ContactDetails collection. Then, depending on what you wanted, you could sort the collection using any of the comparers you had created and not just the name.

0
 
LVL 23

Accepted Solution

by:
wdosanjos earned 50 total points
ID: 35202615
I think it should be something like this:

if (thisName != "")
{ //This creates a new contact 'c' when the Create Contact button on the form is pressed and adds it to the datalist.

	ContactDetails c = new ContactDetails();
	
	c.Name = thisName;
	c.Mobile = thisMobile;
	c.Secphone = thisSecphone;
	c.Email = thisEmail;
	c.Website = thisWebsite;
	c.Address = thisAddress;
	c.Notes = thisNotes;
	contactlist.Add(c);
	
	contactlist.Sort( (x, y) => x.Name.CompareTo(y.Name) );
	
	UpdatelistNames();

Open in new window

0
 
LVL 15

Expert Comment

by:Russell_Venable
ID: 35202987
       ContactDetails c = new ContactDetails();
       
        c.Name = thisName;
        c.Mobile = thisMobile;
        c.Secphone = thisSecphone;
        c.Email = thisEmail;
        c.Website = thisWebsite;
        c.Address = thisAddress;
        c.Notes = thisNotes;

List<string> contactlist = new List<string>(c);

contactlist.Sort(); //sorts your list alphanumerically automatically in ascending order. If you want to sort by length I would suggest using Linq.

var newcontactlist = from element in contactlist orderby element.Length  select element;

UpdatelistNames();
0
 

Author Comment

by:Bronco78th
ID: 35203302
jdavistx: Unless im being very thick WPF listboxes has no Sorting built in at all.

WinForms has but the behavior still has to be programmed (i.e no properties on the control to sort by Alphabetical,index,Numerical etc)

Cheers for the links, saved for future refs anyway!

wdosanjos: That did it, still not quite understanding how x and y tells the list to Sort alphabetically though.

Russell_Venable: Had a quick go with your solution, but received errors on at the "new List<string>(c);"
section.

Anyway, Many thanks for the swift replies.

John
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 35206922
Bronco,

wdosanjos' solution uses a Lambda expression (http://msdn.microsoft.com/en-us/library/bb397687.aspx) as a parameter to one of the List.Sort() overloads (http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx)

The input values (x,y) have their type inferred by the compiler as ContactDetails because of the collection they belong to.  You could call them whatever you wanted.

So, using those as inputs, he can then perform a string comparison of the .Name field of the objects x and y by using the .CompareTo() method of string (http://msdn.microsoft.com/en-us/library/35f0x18w.aspx).
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

707 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

18 Experts available now in Live!

Get 1:1 Help Now