using System;
using System.Collections.Generic;
using System.Linq;
namespace ReOrderList
{
public static class Program
{
static void Main(string[] args)
{
var dataList
= new List
<string>() {"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot"};
var newList = dataList.ToList();
Console.WriteLine("newList List Data");
foreach (var data in dataList){
Console.WriteLine(data);
}
newList = newList.MoveItem(0, 4);
Console.WriteLine("\nRevised List Data: newList.MoveItem(0, 4)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(0, 5);
Console.WriteLine("\nRevised List Data: newList.MoveItem(0, 5)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(5, 1);
Console.WriteLine("\nRevised List Data: newList.MoveItem(5, 1)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(5, 0); //<<<<<revised was (5, 1)
Console.WriteLine("\nRevised List Data: newList.MoveItem(5, 0)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(1, 1);
Console.WriteLine("\nRevised List Data: newList.MoveItem(1, 1)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(0, -1);
Console.WriteLine("\nRevised List Data: newList.MoveItem(0, -1)");
foreach (var data in newList){
Console.WriteLine(data);
}
newList = newList.MoveItem(0, 6);
Console.WriteLine("\nRevised List Data: newList.MoveItem(0, 6)");
foreach (var data in newList){
Console.WriteLine(data);
}
}
}
public static class ListExtensions
{
public static List<T> MoveItem<T>(this List<T> list, int oldIndex, int newIndex)
{
// return unchanged if index's are outside scope
if ((oldIndex == newIndex) ||
(oldIndex < 0) ||
(oldIndex >= list.Count) ||
(newIndex < 0) ||
(newIndex >= list.Count))
return list;
T dataToMove = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, dataToMove);
return list;
}
}
}