动态获取数组长度 [英] Get array length dynamically

查看:147
本文介绍了动态获取数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个数据读取器,并将该值放在下面的数组中

Hi all,

I have a datareader and put that value in an array like below

Task[] objOfTask;
             myReader = cmd.ExecuteReader();
             int counter=0;
             int index = 0;

            while (myReader.Read())
            {
                counter++;
            }
            objOfTask = new Task[counter];
            while (index < counter)
            {
                    objOfTask[index] = new Task();

                    objOfTask[index].Goal = myReader["goals"].ToString();
                    objOfTask[index].Note = myReader["notes"].ToString();
                    objOfTask[index].Status = Convert.ToBoolean(myReader["status"]);

                    index++;
            }

            return objOfTask;



但是在Read()之后,它会重复最后的结果.因此,有什么方法可以在Read()之前获取行数吗?



But after Read(), its repeating the last result. So is there any way to get no of rows before Read() ?

推荐答案

每次调用Read时,它都会获取新行,或者如果没有更多行行返回false.
所以你的while循环:
Each time you call Read, it fetches a new row, or if there are no more rows returns false.
So your while loop:
while (myReader.Read())
{
    counter++;
}

已成功获取并丢弃了每一行.
而是使用列表,并且只循环一次:

Has successfully fetched and discarded each and every row.
Instead, use a List, and only loop the once:

List<Task> list = new List<Task>();
while (myReader.Read())
{
    Task t = new Task();

    t.Goal = myReader["goals"].ToString();
    t.Note = myReader["notes"].ToString();
    t.Status = Convert.ToBoolean(myReader["status"]);
    list.Add(t);
}
return list.ToArray();


我很想像这样重写代码,因为它将两个循环减少到只有一个,并且仍然可以工作:

I would be tempted to rewrite the code like so, since it reduces two loops to just one and would still work:

List<task>tasks = new List<task>();
            myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                Task t = new Task();
                t.Goal = myReader["goals"].ToString();
                t.Note = myReader["notes"].ToString();
                t.Status = Convert.ToBoolean(myReader["status"]);
                tasks.Add(t);
            }

            return tasks;



因为DataReader是仅向前的游标,一次只能移动一个记录,这就是调用Read()时发生的情况,因此这就是为什么需要首先调用它以查看是否有可用数据的原因. HasRows是DataReader的另一个属性,它只能判断是否有可用的行而不是有多少行.



Because a DataReader is a forward only cursor that can only move one record at a time which is what happens when you call Read() and which is why you need to call it in the first place to see if there is data available. HasRows is another property of DataReader that can only tell whether or not there are rows available not how many of them.


这篇关于动态获取数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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