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 C开发者_运维问答ustomer[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
C# Tutorial - Sorting Algorithms
Sorting algorithm
You can also use LINQ Dynamic Sort With LINQ
How to sort an array of object by a specific field in C#?
精彩评论