如果不存在某个数字,如何将某个数字插入到列表中间?
在下面的示例中,我尝试插入数字 4
List<int> list1 = new List<int>(){ 0, 1, 2, 3, 5, 6 };
int must_enter = 4;
if (!list1.Contains(must_enter))
{
list1.Add(must_enter);
}
Run Code Online (Sandbox Code Playgroud)
由于结果编号将在列表末尾输入,但我希望它位于 3 之后(5 之前)。
请注意,由于项目的具体情况,我无法使用排序列表,但列表中的所有数字都保证按升序排列(0,2,6,9,10,...)
编辑:我知道有一个错误,这就是我所做的:
List<int> list0 = new List<int>() { 1, 2, 3, 5, 6 };
int must_enter = 7;
if (!list0.Contains(must_enter))
{
if (must_enter < list0.Max())
{
int result = list0.FindIndex(item => item > must_enter || must_enter > list0.Max());
list0.Insert(result, must_enter);
}
else
{
list0.Add(must_enter);
}
}
Run Code Online (Sandbox Code Playgroud)
edit2:无论如何,由于几个因素,我已经切换到 BinarySearch 方法。大家感谢您的帮助!
你可以这样做:
int index = list1.BinarySearch(must_enter);
if (index < 0)
list1.Insert(~index, must_enter);
Run Code Online (Sandbox Code Playgroud)
这样您就可以保持列表的排序并保持最佳性能。