1

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...

User 68
  • 11
  • 1
  • 2

6 Answers6

10

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));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
8

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

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
  • 2
    `OrderBy` is available on anything implementing `IEnumerable`, including a normal array. Still, +1 from me – Isak Savo May 30 '11 at 11:06
4

In ascending order by Start:

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

And descending order by Start:

var sortedCustomers = customer.OrderByDescending(c => c.Start);
aligray
  • 2,812
  • 4
  • 26
  • 35
1

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

Deepesh
  • 5,346
  • 6
  • 30
  • 45
1

you need to implement IComparable for your Customer class.

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

ibram
  • 4,414
  • 2
  • 22
  • 34
1

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#?

Community
  • 1
  • 1
Bastardo
  • 4,144
  • 9
  • 41
  • 60