例如 定义 :
int[,] a1=new int[5,5];
int[,] a2=new int[5,5];
如何将这两个对象添加到list数组中去,并且如何访问。
(c#) 如何在List中添加二维数组
答案:3 悬赏:10 手机版
解决时间 2021-02-07 06:46
- 提问者网友:蓝琪梦莎
- 2021-02-06 17:54
最佳答案
- 五星知识达人网友:春色三分
- 2021-02-06 18:24
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] x = { 1, 2, 3, 4 };
Console.WriteLine("插入前");
PrintArray(x);
try
{
x = InsertNumber(x, 10, 4);
Console.WriteLine("在 Index=4 处插入10后");
PrintArray(x);
x = InsertNumber(x, 100, 0);
Console.WriteLine("在 Index=0 处插入100后");
PrintArray(x);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
///
/// 将value 插入到指定数组的指定的位置
///
/// 指定数组
/// 待插入的元素
/// 插入的位置
///插入后的数组
static int[] InsertNumber(int[] a, int value, int index)
{
try
{
//转换成List集合
List list = new List(a);
//插入
list.Insert(index, value);
//从List集合,再转换成数组
return list.ToArray();
}
catch (Exception e) // 捕获由插入位置非法而导致的异常
{
throw e;
}
}
///
/// 打印数组
///
static void PrintArray(int[] a)
{
foreach (int x in a)
{
Console.Write("{0} ", x);
}
Console.WriteLine();
}
}
}
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] x = { 1, 2, 3, 4 };
Console.WriteLine("插入前");
PrintArray(x);
try
{
x = InsertNumber(x, 10, 4);
Console.WriteLine("在 Index=4 处插入10后");
PrintArray(x);
x = InsertNumber(x, 100, 0);
Console.WriteLine("在 Index=0 处插入100后");
PrintArray(x);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
///
/// 将value 插入到指定数组的指定的位置
///
/// 指定数组
/// 待插入的元素
/// 插入的位置
///
static int[] InsertNumber(int[] a, int value, int index)
{
try
{
//转换成List
List
//插入
list.Insert(index, value);
//从List
return list.ToArray();
}
catch (Exception e) // 捕获由插入位置非法而导致的异常
{
throw e;
}
}
///
/// 打印数组
///
static void PrintArray(int[] a)
{
foreach (int x in a)
{
Console.Write("{0} ", x);
}
Console.WriteLine();
}
}
}
全部回答
- 1楼网友:酒者煙囻
- 2021-02-06 20:09
ArrayList本身只支持1维,如果要实现2维的话,一种做法是ArrayList里面再放ArrayList。
ArrayList list = new ArrayList();
for(int i = 0; i < 5; i++){
list.Add(new ArrayList());
}
可以这样访问:
object obj = list[a][b];
这样可以么?
- 2楼网友:妄饮晩冬酒
- 2021-02-06 19:55
这个要与年份相关联的吧,有闰年的存在,二月不是个定数……
int year = 1999;//年份变量,可以动态获取一个,只要赋给这个变量就可以了
int[][] date = new int[12][];//二维数组
for(int i = 0;i< date.length;i++)
{
int day = 31;//每月天数
switch(i+1){ case 4: day = 30; break; case 6: day = 30; break; case 9: day = 30; break; case 11: day = 30; break; case 2: day = 28; if(year % 4 == 0)//判断闰年
{ if(i % 100 != 0 || i%400 ==0)
{ day = 29; } } break; default: break; }
date[i] = new int[day];//日期数组
for(int j=0;j<day;j++)
{
date[i][j] = j+1;//为日期赋值
}
}
使用的时候:
for(int i = 0;i< date.length;i++)//遍历操作
{ for(int j=0;j<date[i].length;j++){ 具体操作; }
}
也可以根据月份获得日期数组,例如,获得二月:
int[] month_2 = date[1];
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯