如何在SqlDataReader之前知道或获取数组大小?并将其作为json返回

本文关键字:返回 json 数组 SqlDataReader 获取 | 更新日期: 2023-09-27 18:20:53

我想知道我的数组的大小,以便循环所需的时间,但我不知道如何以有效的方式进行,我能想到的唯一方法是将它放在读取器中并计数,然后使用另一次读取器并插入值:(我是的学生

这是代码

myConnection.Open();
SqlCommand sqlCommand = new SqlCommand(" SELECT * FROM table ", myConnection);
SqlDataReader dr = sqlCommand.ExecuteReader();
Calendar[] loArrayRegistrosCalendario = new Calendar[200]; //200 As an example
if (dr != null)
{
    int i = 0;
    while (dr.Read())
    {
        Calendar loRegistroDia = new Calendar();
        loRegistroDia.User = (dr["user"].ToString());
        loArrayRegistrosCalendario[i] = loRegistroDia;
        i = i + 1;
    }
}
return loArrayRegistrosCalendario;

如何在SqlDataReader之前知道或获取数组大小?并将其作为json返回

您根本不需要数组。

myConnection.Open();
var loArrayRegistrosCalendario = new List<Calendar>();
using (SqlCommand sqlCommand = new SqlCommand(" SELECT * FROM table ", 
  myConnection);)
{
  using (SqlDataReader dr = sqlCommand.ExecuteReader())
  {
    if (dr != null)
    {
      while (dr.Read())
      {
        Calendar loRegistroDia = new Calendar();
        loRegistroDia.User = (dr["user"].ToString());
        loArrayRegistrosCalendario.Add(loRegistroDia);
      }
    }
  }
}
return loArrayRegistrosCalendario;

(附带说明一下,请正确处理IDisposable对象,例如SqlCommand和SqlDataReader应该正确处理。我建议两者都使用using()语句。)

序列化日历数组和日历列表将产生相同的结果:DotNetFiddle示例。

public class Program
{
    public static void Main()
    {
        var myobject = new MyObject();
        myobject.Calendars1 = new List<Calendar>();
        for (DateTime dt = new DateTime(1980,1,1); dt <= new DateTime(1981,1,1); dt = dt.AddMonths(1))
        {
            myobject.Calendars1.Add(new Calendar() { Name =  dt.ToString("MMMM") });
        }
        
        myobject.Calendars2 = myobject.Calendars1.ToArray();
        
        var json1 = JsonConvert.SerializeObject(myobject.Calendars1);
        var json2 = JsonConvert.SerializeObject(myobject.Calendars2);
        
        Console.WriteLine(json1);
        Console.WriteLine(json2);
    }
}
public class MyObject
{
    public List<Calendar> Calendars1 { get; set; }
    public Calendar[] Calendars2 { get; set; }
}
public class Calendar
{
    public string Name { get; set; }
}

结果:

[{quot;姓名":"一月"},{quotquot;名称"二月"},{quot名称":"三月"},{&quot名称:"四月"},},{"姓名":"八月"},

[{quot;姓名":"一月"},{quotquot;名称"二月"},{quot名称":"三月"},{&quot名称:"四月"},},{"姓名":"八月"},

只需创建一个SQL命令即可获得如下计数:

SqlCommand sqlCommand = new SqlCommand(" SELECT Count (*) FROM table ", myConnection);
int rows = sqlCommand.ExecuteScalar();
Calendar[] loArrayRegistrosCalendario = new Calendar[rows];