C# 移动列表中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14628782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:29:42  来源:igfitidea点击:

Move elements in list

c#.netlistdata-structures

提问by Jacek

I declare following object

我声明以下对象

List<string> list = {"Kate", "John", "Paul", "Eve", "Hugo"};

I would like to move "Eve" at front of my list? How can I do that. I must not to reorder other elements!
At output I want to get this

我想将“Eve”移到我的列表前面?我怎样才能做到这一点。我不能对其他元素重新排序!
在输出我想得到这个

"Eve", "Kate", "John", "Paul", "Hugo"

采纳答案by Cédric Bignon

list.Remove("Eve");  // Removes the first "Eve" element in the list
list.Insert(0, "Eve");  // Inserts "Eve" at the first position in the list

However, if your list contains multiple "Eve"s, calling Remove("Eve") will only remove the first occurrence of "Eve".

但是,如果您的列表包含多个“Eve”,则调用 Remove("Eve") 只会删除第一次出现的“Eve”。

And you have to know that inserting element at the beginning of a list is an expensive operation. Because all elements already in the list have to be shifted.

而且您必须知道在列表的开头插入元素是一项昂贵的操作。因为列表中已经存在的所有元素都必须移动。

UPDATE

更新

As @AlvinWong commented, LinkedList<string>is a very good solution to avoid this overhead when inserting an element. The Insertoperation is done in O(1) (O(n-i) in a List). The major drawback of LinkedList<string>is that accessing the ith element is an operation in O(i) (O(1) in a List).

正如@AlvinWong 评论的那样,这LinkedList<string>是一个很好的解决方案,可以在插入元素时避免这种开销。该Insert操作在 O(1) 中完成(O(ni) in a List)。的主要缺点LinkedList<string>是访问第ith 个元素是 O(i) 中的操作(a 中的 O(1) List)。

回答by Soner G?nül

You can remove and insert it to first index.

您可以将其删除并将其插入到第一个索引中。

List<string> list = new List<string>(){ "Kate", "John", "Paul", "Eve", "Hugo" };
list.Remove("Eve");
list.Insert(0, "Eve");
foreach (var i in list)
{
   Console.WriteLine(i);
}

If you know your specific index of "Eve", you can remove it with List.RemoveAt()method.

如果您知道 的特定索引"Eve",则可以使用List.RemoveAt()方法将其删除。

Here is a DEMO.

这是一个DEMO.

回答by Grant Thomas

You can use the List.RemoveAt(so you don't remove allEve's) and List.Insert.

您可以使用List.RemoveAt(因此您不会删除所有Eve) 和List.Insert.

回答by onkar

You can use RemoveAt method to remove Eve from the given index and use Insert to add the Eve at the start of the list.

您可以使用 RemoveAt 方法从给定的索引中删除 Eve,并使用 Insert 将 Eve 添加到列表的开头。

回答by Fredrick Gauss

list.Remove("Eve");
list.Insert(0, "Eve");