如何使用c#将数组添加到第n个位置? [英] How to add to array to n th position using c#?

查看:480
本文介绍了如何使用c#将数组添加到第n个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的数组



  int  [] marks =  new   int  [ 5 ] { 99  98  95 }; 



这意味着

现在我想在第二个位置插入标记96,e



我试过很多方法的逻辑是什么请帮助



我尝试了什么:



  int  [] marks =  new   int  [ 5 ] { 99  98  95 }; 



表示

int [0] = 99

int [1] = 98

int [2] = 95



现在我想在第2个位置插入标记96,e



int [0] = 99

int [1] = 98

int [2] = 96

int [3] = 95



我试过很多方法的逻辑是什么请帮助

解决方案

你做不到用数组。为此,您可能希望使用列表< T>

List(T)类(System.Collections.Generic) [ ^ ]

列表与LT; INT> marks =  new  List< int>(){ 99  98  95 };  //  初始化包含3个值的列表 
marks.Insert( 2 96 ); // 在索引'2'处插入值'96'


在数组中插入有点复杂 - 您必须先将所有较高索引值移开,然后将值保存在数组中。

 [0 == 99] [1 == 98] [2 == 95] [3 ==空] 



 [0 == 99] [1 == 98] [2 == 95] [3 == 95] 



 [0 == 99] [1 == 98] [2 == 96] [3 == 95] 

这很复杂,因为你必须首先确保阵列中有足够的空间,然后从高索引结束工作并手动复制每个值。



而是使用List< int>并且你会发现它有一个Insert方法可以为你完成所有这些:

 List< int> marks =  new  List< int> { 99  98  95 }; 
marks.Insert( 2 96 );


i have array like

int [] marks = new int[5]  { 99,  98, 95};


it means
now i want to insert marks 96 in 2rd postion i,e

what is the logic i have tried many ways please help

What I have tried:

int [] marks = new int[5]  { 99,  98, 95};


it means
int[0]=99
int[1]=98
int[2]=95

now i want to insert marks 96 in 2rd postion i,e

int[0]=99
int[1]=98
int[2]=96
int[3]=95

what is the logic i have tried many ways please help

解决方案

You can't do that with an array. For this purpose, you might want to use a List<T>:
List(T) Class (System.Collections.Generic)[^]

List<int> marks = new List<int>() { 99, 98, 95 }; // initialize a list with 3 values
marks.Insert(2, 96); // insert value '96' at index '2'


Inserting in an array is a little complicated - you have to move all the "higher index" values out of the way first and then save the value in the array.

[0 == 99][1 == 98][2 == 95][3 == empty]


[0 == 99][1 == 98][2 == 95][3 == 95]


[0 == 99][1 == 98][2 == 96][3 == 95]

That's complicated, because you have to first make sure there is enough room in the array, then work from the "high index end" and manually copy each value.

Instead, use a List<int> and you'll find it has an Insert method which does all that for you:

List<int> marks = new List<int> { 99,  98, 95};
marks.Insert(2, 96);


这篇关于如何使用c#将数组添加到第n个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆