Array中数据强制数据类型转换

因为工作需要,有工作中需要大量的把string数组转换成为int数组

我们知道如果需要转换string数组当中的所有数所成为int有一个非常传统的方法
以下是测试demo


string[] strs = new string[] "1""2""3" };
int[] numbers = new int[strs.Length];
for (int i = 0; i < strs.Length; i++)
  {
      numbers[i] 
= Convert.ToInt32(strs[i]);
  }

其实ms在VS当中提供了一个非常实用的方法可以供我们使用直接进行转换的,不过其原理其实也是一样
那就是Array.ConvertAll这个方法
MSDN描述为

public static TOutput[] ConvertAll<TInput, TOutput>(
TInput[] array,
Converter<TInput, TOutput> converter
)

其中参数分别为:TInput 为源数组类型,TOutput为目标数组类型 ,array当然即为源数组,而converter为一个委托
这个所提供的功能即为把数据从一种数据类型转换另一种数据类型的一个方法.

以下是我使用demo

public static int ConvertStrToInt(string source)
{

   
return Convert.ToInt32(source);

}

string[] strs = new string[] { "1""2""3" };
for (int i = 0; i < strs.Length; i++)
{
    Console.WriteLine(strs[i].GetType().ToString());
}

Converter
<stringint> myConvert = new Converter<stringint>(ConvertStrToInt);
int[] numbers = Array.ConvertAll<string,int>(strs, myConvert);
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i].GetType().ToString());
}

在这里还补充一点
我们知道在建立数组初始化时必须指定其数组容量,否则就会报错
但我们如果确实不确定数组的容量为多少时,应该怎么解决呢,当然,应该ArrayList这类对象当然是可以的
不过就数组这个问题在这里我找到一个方法,也欢迎大家指出.
以下是使用demo

int []arr = new int[0];
        
for (int i = 0; i < GridView1.Rows.Count; i++)
{
    
if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
    {
       CheckBox cbSelect 
= GridView1.Rows[i].Cells[6].FindControl("cbxSelect"as CheckBox;
                
       
if (cbSelect.Checked)
       {
           
int[] temp = new int[arr.Length + 1];
           Array.Copy(arr, temp, arr.Length);
           temp[arr.Length] 
= Convert.ToInt32(GridView1.DataKeys[i].Value);
           arr 
= temp;
       }
     }
}

在这里说一下我的具体是什么,在一个数据列表当中我需要获取到所有选定了的数据主键值,然而我不知道具体用户选择了几个,所以这个数据的大小无法确定,所以在这里采用一个中间数组的方法进行中继处理,每次发现选中则把用数据容量大1的数组去记录,并且把其值存储下来,最后那个临时数组即为我们想要的值。
当然在效率方面没有考虑,个人不建议使用
朋友们有好的意见一起分享^_^



posted on 2008-06-21 11:51  西门潇洒  阅读(3144)  评论(2编辑  收藏  举报