Solved

Sorting a List<> alphabetically

Posted on 2011-03-23
5
952 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

705 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