New_Boy_2020 New_Boy_2020 - 2 months ago 12
Vb.net Question

Vb.net / C# - sort list/array starting from a mid point

Is there an easy way to sort a list starting at a particular value?

A B C D E F

So we can start from a passed in value say 'C'

C D E F A B

I want optimise a time slot list and it will be best to sort the order from a starting time so it doesn't need to iterate all times it doesn't need to.

Answer

You could use:

ArrayList.Sort(int index, int count, IEqualityComparer comparer)

This method sorts the elements in a range of elements in ArrayList using the specified comparer.

Parameters

index

Type: System.Int32 The zero-based starting index of the range to sort.

count

Type: System.Int32

The length of the range to sort.

comparer

Type: System.Collections.IComparer The IComparer implementation to use when comparing elements.

-or-

A null reference (Nothing in Visual Basic) to use the IComparable implementation of each element.

There is an example right here explaining how to use it.

ArrayList.Sort Method

If you don't know how to implement the Equality comparer you can check this post too

Update:

From your array: A B C D E F

Let's suppose that it is in this object and it is instantiated:

List<string> array;

So you can do this:

public List<string> foo(List<string> array, int i) { 
  array.Sort(i, array.size() - i, null);
  List<string> aux = array.Skip(i).Take(array.Size() - i );
  aux.AddRange(array.Take(i));
  return aux;
}

and you call it like this:

List<string myNewArray = foo(array, 2);