C#中的List<int>如何在两个值之间插入新值?

45

我有一个列表,需要不断添加新值,但每次添加后,我需要将其递增并插入到两个值之间。

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

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

所以初始化程序将有1、3个值。

然后我将处理一组新的数字。初始化程序需要有以下值:

1、5、3、7

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

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

我知道如何生成正确的新值,只需要帮助在现有的初始化程序值之间插入它,而不必添加2或3个循环来移动值的位置。


3
请阅读文档:http://msdn.microsoft.com/zh-cn/library/sey5k5z4(v=vs.80).aspx - Dima
甚至可以搜索 - http://stackoverflow.com/questions/460223/whats-a-good-way-to-insert-something-in-the-middle-of-a-list,或者https://dev59.com/rGDVa4cB1Zd3GeqPhuez 或者... - dash
5个回答

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

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

int index = initializers.IndexOf(3);
initializers.Insert(index, 2);
给你1、2、3。

谢谢!但是如果您不知道列表中是否有“3”怎么办?(我只想无论列表中是否有其他内容,都将我的列表项添加到索引0) - Kokodoko
你可以使用Count()和Any()来检查是否存在3。 - Christoph B

21

我明白了。我不知道这个存在。哈哈。我是C#的新手。谢谢! - gdubs

5

对于那些寻求更复杂功能(比如在两个值之间插入多个项,或者不知道如何在列表中查找项的索引)的人,这里是答案:

在两个值之间插入一个项目非常容易,就像其他人已经提到的那样:

myList.Insert(index, newItem);

通过使用InsertRange方法,插入多个项也很容易:

myList.InsertRange(index, newItems);

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

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

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

0

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

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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接