Solved

Sorting a List<> alphabetically

Posted on 2011-03-23
5
936 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

832 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