Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting the myClass array

Status
Not open for further replies.

graabein

Programmer
Oct 9, 2002
186
NO
Hi,

I have a list of objects I want sorted by different properties. For example a list of customers that I want sorted by name, address or birth date.

Code:
public class Customer
{
   private string name;
   private string address;
   private DateTime birthDate;
   ...
}

...

Customer[] customers = myDataAccess.GetAllCustomers();

I don't want to reload the array each time with a sort parameter. I've looked at the Array.Sort method but I haven't figured it out. Any help would be much appreciated.

[elephant2]
graabein
 
Another way is to use a DataTable object and put data of each Customer object in one row.
Next use a DataView to apply sort on any column in the Customer DataTable and also perform filters:

DataTable dtCust = new DataTable();
Fiil the dtCust table with data from a DB using a DataAdapter
// Now the dtCust table will have columns such as: name, address, birthDate
You no need to build an array of all customers. It is also stored in the dtCust.Rows.
DataView myDataView = dtCust.DefaultView;
myDataView.Sort = "name, birthDate DESC"; // Sort ASC by name and DESC by birthDate
Use myDataView object to bind to a DataGrid or do other things.
// Filter
myDataView.RowFilter = "name = 'George'";
myDataView.Sort = "birthDate DESC";
// The above returns only the records with name equal to 'George' and sorted in DESC ordrer by birthDate.

-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top