简体   繁体   中英

sort an array of a class in C#

In my program, I have a class like this:

Class Customer{

    double Start;
    double Finish;
    double Wait;
}

and I created an array of this class:

Customer[] customer = new Customer[300];

How I can sort this array according to Start values Descending or Ascending?

Thanks...

You could use the Array.Sort method to sort the array in-place:

Array.Sort(customer, (x, y) => x.Start.CompareTo(y.Start));

or in descending order

Array.Sort(customer, (x, y) => y.Start.CompareTo(x.Start));

If would prefer to use a List of Customer , however you can apply the same function on the array :

List<Customer> customerList = new List<Customer>;
var orderedCustomerList = customerList.OrderBy(item => item.Start);

Refer to:

Enumerable.OrderBy Method

Enumerable.OrderByDescending Method

In ascending order by Start :

var sortedCustomers = customer.OrderBy(c => c.Start);

And descending order by Start :

var sortedCustomers = customer.OrderByDescending(c => c.Start);

you need to use icomparer and you need to write your custom code after implementing icomparer in your class

you need to implement IComparable for your Customer class.

http://msdn.microsoft.com/en-us/library/system.icomparable%28v=vs.80%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM