Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Sorting a List<> alphabetically

Posted on 2011-03-23
5
Medium Priority
?
974 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 200 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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Integration Management Part 2

927 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