How would one create a method that takes an integer i
, and move the member of a List<T>
at index i
from its current position to the front of the list?
views:
85answers:
4
+3
A:
The List<T> class doesn't offer such a method, but you can write an extension method that gets the item, removes it and finally re-inserts it:
static class ListExtensions
{
static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
{
T item = list[index];
list.RemoveAt(index);
list.Insert(0, item);
}
}
dtb
2010-04-04 19:28:27
Nice extension.
vittore
2010-04-04 19:31:39
the header for the method is supposed to be like this:public void MoveToFront(int i)
Shonna
2010-04-04 19:31:55
Okay, since you _know_ the signature I'm boldly claiming that this is homework. Tag it as that next time.
Benjamin Podszun
2010-04-04 19:34:54
@Shonna: the method needs a reference to the list. You need to pass that in or change my code to access the list in a different way which should be simple enough.
dtb
2010-04-04 19:35:25
A:
var l = new List<DataItem>();
var temp = l[index];
l.RemoveAt(index);
l.Insert(0, temp);
vittore
2010-04-04 19:29:29
+1
A:
Try this
static List<int> idList = new List<int>() { 1, 2, 4, 5, 6, 8, 9 };
private static void moveListItem(int index)
{
int getIndex = 0;
foreach (int item in idList)
{
Console.WriteLine(" Before Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex);
getIndex++;
}
int value = idList[index];
idList.RemoveAt(index);
idList.Insert(0, value);
Console.WriteLine();
getIndex = 0;
foreach (int item in idList)
{
Console.WriteLine(" After Id List Value - {0} ,Index - {1} ", item.ToString(), getIndex);
getIndex++;
}
}
Wonde
2010-04-04 19:40:32
A:
Any of the 3 answers so far do the trick, but instead of doing a RemoveAt and a Insert operation, I would suggest moving each item one place to the right from the desired positions left, to the beginning of the list. That way you avoid moving the items placed at the right of the item moved.
This is a modification of @dtb's answer.
static class ListExtensions
{
static void MoveItemAtIndexToFront<T>(this List<T> list, int index)
{
T item = list[index];
for (int i = index; i > 0; i--)
list[i] = list[i - 1];
list[0] = item;
}
}
Fede
2010-04-05 03:06:05