【发布时间】:2014-10-22 19:11:27
【问题描述】:
我有两个列表,一个是原始的,另一个是原始列表的副本
List<Button> buttonList; // this is the original list
List<Button> copyButtonList;// this is the copy of button list; this use to sort the list
我想根据我在单独类中编写的自定义插入排序对copyButtonList 进行排序
我按照以下方式克隆原始列表以复制列表并对其进行排序
copyButtonList = buttonList.ToList();
String s = SortEngine.insertionSort(copyButtonList);
msgList.Items.Add(s);
我也尝试以下方法
copyButtonList = new List<Button>(buttonList);
和
foreach (var b in buttonList) {
copyButtonList.Add(b);
}
之后我尝试按如下方式打印这两个列表
foreach(var b in buttonList){
msgList.Items.Add(b.Text);
}
foreach(var b in copyButtonList){
msgList.Items.Add(b.Text);
}
在上述三种情况下,两个列表都是排序的:( 我只想对copyButtonList进行排序,谁能指出我在这里做的错误?
更新:我的插入排序算法如下
public static String insertionSort(List<Button> button)
{
String key;
int i = 0;
int j;
String s = "";
for (j = 1; j < button.Count; j++)
{
key = button.ElementAt(j).Text;
i = j - 1;
while (i >= 0 && int.Parse(button.ElementAt(i).Text) > int.Parse(key))
{
button.ElementAt(i + 1).Text = button.ElementAt(i).Text;
i = i - 1;
}
button.ElementAt(i + 1).Text = key;
if (i == -1)
{
s=(button.ElementAt(i + 1).Text + " is the starting Item, keep this in before " + button.ElementAt(i + 2).Text);
}
else if (i == j - 1)
{
s=(button.ElementAt(i + 1).Text + " is the last Item, keep this in after " + button.ElementAt(i).Text);
}
else
{
s=(button.ElementAt(i + 1).Text + " is between " + button.ElementAt(i).Text + " and " + button.ElementAt(i + 2).Text);
}
}
if (button.Count == 1)
{
s= ("This is the first Item");
}
return s;
}
【问题讨论】:
-
列表的3种浅克隆方法都是正确的。你的问题出在其他地方。
-
@Athari 是对的......你想对副本做什么?
-
愚蠢的问题:您是否在排序之前验证了两个列表的排序顺序?
-
哦!另一个愚蠢的问题:您的
insertionSort是如何实现的?你交换文本而不是列表中的索引位置吗? -
@Andre 我只想对副本进行排序而不影响原件
标签: c# list generics collections clone