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

1
  • 1
    You may want to specify if LINQ is an option or not. Commented May 30, 2011 at 11:03

6 Answers 6

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));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

OrderBy is available on anything implementing IEnumerable<T>, including a normal array. Still, +1 from me
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);

Comments

1

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

Comments

1

you need to implement IComparable for your Customer class.

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.