0

I want to change data position in array when user select date in listbox.i will show you in my Example question

array = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

if user select text="Mar" value = 3 in listbox result array should be change look like this::

array = {"Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb"}

how can i do like this. Thank you.

user3001046
  • 235
  • 1
  • 10
  • 28
  • 3
    It is strongly recommended that you learn to use proper data structures to represent data rather than putting everything in a bunch of strings. ASP.Net is not PHP. – Federico Berasategui May 12 '14 at 03:03
  • @HighCore looks more like [LISP](http://en.wikipedia.org/wiki/CAR_and_CDR) task :) of moving "first item to end of list" several times... – Alexei Levenkov May 12 '14 at 03:09
  • Possible duplicate of: [Easiest way to Rotate a List in c#](http://stackoverflow.com/questions/9948202/easiest-way-to-rotate-a-list-in-c-sharp) – Ulugbek Umirov May 12 '14 at 08:00

2 Answers2

2
var array = new[] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

var value = 3; // value >= 1

array = array.Skip(value - 1).Concat(array.Take(value - 1)).ToArray();

or

array = array.Select((_, i) => array[(i + value - 1) % array.Length]).ToArray();

produces:

Mar Apr May Jun Jul Aug Sep Oct Nov Dec Jan Feb

Martin Booth
  • 8,485
  • 31
  • 31
1

I believe the most efficient way will be this:

public string[] ShiftArray(string[] array, int shiftBy)
{
    string[] newArray = new string[array.Length];

    Array.Copy(array,  shiftBy, newArray, 0, array.Length - shiftBy);
    Array.Copy(array,  0, newArray, array.Length - shiftBy, shiftBy);

    return newArray;
}
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59