c#list<int> 如何在两个值之间插入一个新值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10110872/
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-09 12:28:19  来源:igfitidea点击:

c# list<int> how to insert a new value in between two values

c#asp.netlist

提问by gdubs

so i have a list where i need to add new values constantly but when i do i need to increment it and insert it in between two values.

所以我有一个列表,我需要在其中不断添加新值,但是当我这样做时,我需要增加它并将其插入两个值之间。

List<int> initializers = new List <int>();

initializers.Add(1);
initializers.Add(3);

so initializers would have 1, 3 values.

所以初始值设定项将有 1, 3 个值。

i would then process a new set of numbers. the initializers will need to have the values.

然后我会处理一组新的数字。初始值设定项将需要具有值。

1, 5, 3, 7

1, 5, 3, 7

and if i process another set of numbers it should become

如果我处理另一组数字,它应该变成

1, 9, 5, 13, 3, 11, 7, 15

1, 9, 5, 13, 3, 11, 7, 15

i know how to properly generate the new values inserted, i just need some help on inserting it in between the existing values of the initializers without having to add 2 or 3 more loops to move the values' positions.

我知道如何正确生成插入的新值,我只需要一些帮助就可以将它插入到初始值设定项的现有值之间,而不必再添加 2 或 3 个循环来移动值的位置。

采纳答案by Phil

List<int> initializers = new List <int>();

initializers.Add(1);
initializers.Add(3);

int index = initializers.IndexOf(3);
initializers.Insert(index, 2);

Gives you 1,2,3.

给你 1,2,3。

回答by Grant Thomas

Use List<T>.Insert:

使用List<T>.Insert

initializers.Insert(index, value);

回答by Lam Tran Duy

You can just use List.Insert()instead of List.Add() to insert items at a specific position.

您可以只使用List.Insert()而不是 List.Add() 在特定位置插入项目。

回答by Elideb

Another approach, if there is a computationally viable way of sorting the elements, is:

另一种方法,如果有一种计算上可行的元素排序方法,是:

list.Insert(num);
// ...
list.Insert(otherNum);

// Sorting function. Let's sort by absolute value
list.Sort((x, y) => return Math.Abs(x) - Math.Abs(y));

回答by Mehdi Dehghani

For those who are looking for something more complex (inserting more than one item between 2 values, or don't know how to find the indexof an item in a list), here is the answer:

对于那些正在寻找更复杂的东西(在 2 个值之间插入多个项目,或者不知道如何index在列表中找到项目的)的人,这里是答案:

Insert one item between 2 values is dead easy, as already mentioned by others:

正如其他人已经提到的那样,在 2 个值之间插入一项非常容易:

myList.Insert(index, newItem);

Insert more than one item also is easy, thanks to InsertRangemethod:

插入多个项目也很容易,感谢InsertRange方法:

myList.InsertRange(index, newItems);

And finally using following code you can find the index of an item in list:

最后使用以下代码,您可以在列表中找到项目的索引:

var index = myList.FindIndex(x => x.Whatever == whatever); // e.g x.Id == id