Sort both ways Arraylist of objects

Hello Experts,
I'm a beginer in C#.
I have an arrayList containing LastName, Firstname
What I am trying to achieve is sort both ways (ascending and descending order) on both first name and lastname. Something like: Sort(sortField, sortDirection)
Is there a way to do this in C# ?
Thanks in advance
tech1guyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

devsolnsCommented:
perfect examples here:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemCollectionsArrayListClassSortTopic.asp

The point here is you will need to impletment IComparer so that the arraylist knows "how" to sort the items you want.  Then you will call its sort method and choose ascending/descending order.  That link shows the very same thing you asking, sorting names.

gp
0
Ravi SinghSenior Software EngineerCommented:
Hi, I don't know if theres an easier way, but you could use the class below provided that your ArrayList contains strings formatted as you mentioned "lastname, firstname":

      public class MyNameSorter : IComparer
      {
            public enum SortBy { Firstname, LastName };
            public enum SortType { Ascending, Descending };

            private static SortBy _sb;
            private static SortType _st;

            public static void Sort(ref ArrayList list, SortBy sb, SortType st)
            {
                  _sb = sb;
                  _st = st;
                  list.Sort(new MyNameSorter());
            }
            
            public int Compare(object x, object y)
            {
                  if (_sb == SortBy.Firstname && _st == SortType.Ascending)
                        return ((string) x).Split(',')[1].CompareTo(((string) y).Split(',')[1]);
                  else if (_sb == SortBy.Firstname && _st == SortType.Descending)
                        return ((string) y).Split(',')[1].CompareTo(((string) x).Split(',')[1]);
                  else if (_sb == SortBy.LastName && _st == SortType.Ascending)
                        return ((string) x).Split(',')[0].CompareTo(((string) y).Split(',')[0]);
                  else
                        return ((string) y).Split(',')[0].CompareTo(((string) x).Split(',')[0]);
            }
      }


Example use:

      ArrayList arrayList = new ArrayList();
                  
      arrayList .Add("Smith, John");
      arrayList .Add("Arndale, Guy");
      arrayList .Add("Zain, Chris");

      //Firstname ascending
      MyNameSorter.Sort(ref arrayList, MyNameSorter.SortBy.Firstname, MyNameSorter.SortType.Ascending);

      //Firstname descending
      MyNameSorter.Sort(ref arrayList, MyNameSorter.SortBy.Firstname, MyNameSorter.SortType.Descending);

      //LastName ascending
      MyNameSorter.Sort(ref arrayList, MyNameSorter.SortBy.LastName, MyNameSorter.SortType.Ascending);

      //LastName descending
      MyNameSorter.Sort(ref arrayList, MyNameSorter.SortBy.LastName, MyNameSorter.SortType.Descending);

Hope this helps!
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nil1stCommented:
Hi
You can then use the ArrayList.Sort() method - if your business object implements a System.Collection.IComparer method, you can use that by default by calling Sort() with no parameters, or you can create a new instance of a custom IComparer - the following code demonstrates sorting the product versions loaded in the previous step by name (the ArrayList.Sort() documentation can provide a more extensive example of how to implement a default IComparer in your business object - this example uses external IComparer implementations):

versions.Sort(new ProductVersionNameSortAscending());
// or
versions.Sort(new ProductVersionNameSortDescending());

// sorts ascending by title:
public class ProductVersionNameSortAscending : System.Collections.IComparer
{
    public int Compare(object x, object y)
    {
         return ((Version)x)._title.CompareTo(((Version)y)._title);
    }
}

// sorts descending by title:
public class ProductVersionNameSortDescending : System.Collections.IComparer
{
    public int Compare(object x, object y)
    {
        int i = ((Version)x)._title.CompareTo(((Version)y)._title);
        return (i * -1);
    }
}


BTW... I got this from http://mongoosesolutions.com/mg/forum_posts.aspx?thread_id=771
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

devsolnsCommented:
guys all that is covered in detail in the link i posted.

gp
0
Ravi SinghSenior Software EngineerCommented:
The msdn examples in the link posted doesn't show how to sort an ArrayList based on its elements' substrings ("lastname, firstname"), which I think is what tech1guy is having difficulty with...
0
tech1guyAuthor Commented:
Hi everybody,
Thanks for everyone's response. I think that Zephyr__  knows where I'm stuck. We are near the solution. I've gone through your solution, is there any way that I can get rid of permutation nad combinations for ascending and descending like (if first && ascending order OR firstname && descending order)............... something like: generic kind of thing for any number of columns........
0
tech1guyAuthor Commented:
Hi Zephyr__ ,
My arraylist does NOT contain a strings 'firstname, lastname'..............actually, my arralist contains the objects as columns: like 2 columns (firstname and lastname) and then each column is having their values as follows:

Firstname Lastname
Smith       Don
John         Stepson
Ron          Gill

So, you can say that it's ArrayList of Objects. Actually I'm specifying this ArrayList as Datasource for my DataGrid.
0
Ravi SinghSenior Software EngineerCommented:
Hi, could you be a little clearer on what type your storing in the ArrayList, do you mean your storing DataColumn objects?
0
tech1guyAuthor Commented:
Basically, I'm generating arraylist from database (which is already in business code).......all I've is ArrayList and I'm binding my arraylist to datagrid with two column as firstname and lastname....................it's going fine................the problem is that I am trying to sort the datagrid by clicking the datagrid column heading..............As everything is generated at business end............so, I'm unable to re-execute the sql command..............So, I'm left with the option to sort my ArrayList (which contains Firstname, Lastname and their corresponding values)................... I hope this will be helpful to you in solving my problem.
0
devsolnsCommented:
If your generating the values from a database why put them into an ArrayList at all?  You have all the sorting capablities you need inside of a DataSet/DataTable/DataView.  Check out this piece of code.

   public void BindGrid(String sortfield)
   {
      // Set up the SqlDataAdapter to get the "Authors" table from the
      // "pubs" database.
      SqlDataAdapter myCommand = new SqlDataAdapter("SELECT * FROM " +
         "Authors", myConnection);
      // Fill a new DataSet.
      DataSet ds = new DataSet();
      myCommand.Fill(ds);
      // Create a DataView based on the first (and only) DataTable in the
      // DataSet. Sort the data using the specified sort field.
      DataView view = ds.Tables[0].DefaultView;
      // To sort in ascending order:
      view.Sort = sortfield + " ASC";
      // To sort in descending order:
      // view.Sort = sortfield + " DESC";
      // Bind the DataGrid to the sorted DataView.
      MyDataGrid.DataSource=view;
      MyDataGrid.DataBind();
   }

Another good way to go about it is using the DataTable.Select() method.


gp
0
tech1guyAuthor Commented:
As told by my seniors that in pure OOP and layered design, we have to pass ONLY arraylist to the presentation layer.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.