Solved

Sorting a List<> alphabetically

Posted on 2011-03-23
5
946 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 our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Suggested Solutions

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…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

726 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