我试图获得这种算法的逻辑,但我真的无法得到它,也许我不够聪明......
我有一份清单。这个列表是排序的,假设我有10个项目。
现在用户选择将第9个项目放到第4个位置。
该怎么办?
我的想法:
这个想法是否正确?
答案 0 :(得分:1)
看起来你在谈论轮换。这是一篇有几个想法的文章,并对各种方法的优缺点进行了不错的讨论:
答案 1 :(得分:0)
以下是使用SortedList的示例。您也可以创建一个列表并在其上调用Sort()。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sorter
{
class Program
{
static void Main(string[] args)
{
var list = new SortedList();
var item = new SomeItem(1);
list.Add(item.Value, item);
item = new SomeItem(8);
list.Add(item.Value, item);
item = new SomeItem(2);
list.Add(item.Value, item);
item = new SomeItem(4);
list.Add(item.Value, item);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list.GetByIndex(i));
}
Console.ReadLine();
}
}
public class SomeItem
{
public int Value;
public SomeItem(int value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
}
答案 2 :(得分:0)
执行所有这些单独的移动将是低效的,更好的方法是使用单一Array.Copy
方法执行对象跨度。
我将使用数组代替列表,就像您使用List<T>
一样,您可以使用RemoveAt
和Insert
public static void MoveIndex<T>(this T[] array, int sourceIndex, int destIndex)
{
//Some sanity checks before we start.
var arrayLength = array.Length;
if(sourceIndex >= arrayLength || destIndex >= arrayLength || sourceIndex < 0 || destIndex < 0)
throw new IndexOutOfRangeException("The indexes must be within the array);
if(sourceIndex == destIndex)
throw new ArgumentException("The two indexes must not have the same value");
//Store for later useage
var temp = array[sourceIndex];
int offset;
int length;
//Figure out if we are moving left or right
if(souceIndex < destIndex)
{
offset = -1;
length = destIndex - sourceIndex;
}
else
{
offset = 1;
length = sourceIndex - destIndex;
}
//"Move" the elements that need shifting
Array.Copy(array, sourceIndex, array, sourceIndex + offset, length);
//put back the item that we stored earlier;
array[destIndex] = temp;
}
如果您可以将自己的收藏设为ObservableCollection<T>
,则可以在Move函数