0

I want to know the size of my array to loop just the needed times but I don't know how to do it in an efficient way, the only way that i can think is to put it inside of the reader and count, then use another time the reader and insert the values :( I'm a student

Here is the code

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;
5
  • 3
    Why not use a class (like List<>()) that supports a dynamic number of items, then if you have to use an array you can call .ToArray()? Commented Sep 5, 2014 at 19:21
  • i'have already do it with list but i need a json object that's why i a create a class :C Commented Sep 5, 2014 at 19:22
  • 1
    You can serialize a List to a JSON array as easily as an Array. Commented Sep 5, 2014 at 19:24
  • Really? D: I' ve been investigating for 3 hours to know that i need to make a class and do it as i have to have it serialized :s Commented Sep 5, 2014 at 19:30
  • 1
    Here is an example where I've serialize both a list and an array, they are exactly the same. Be aware your question was a bad question because it was previous to a recent edit, an XY Problem. Commented Sep 5, 2014 at 19:36

2 Answers 2

2

You simply do not need an array at all.

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;

(As a side note, please dispose of IDisposable object properly, for example the SqlCommand and SqlDataReader should be Disposed of properly. I would recommend using the using() statement for both.)

Serializing an Array of Calendar and List of Calendar will produce the same results: DotNetFiddle Example.

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; }
}

Results:

[{"Name":"January"},{"Name":"February"},{"Name":"March"},{"Name":"April"},{"Name":"May"},{"Name":"June"},{"Name":"July"},{"Name":"August"},{"Name":"September"},{"Name":"October"},{"Name":"November"},{"Name":"December"},{"Name":"January"}]

[{"Name":"January"},{"Name":"February"},{"Name":"March"},{"Name":"April"},{"Name":"May"},{"Name":"June"},{"Name":"July"},{"Name":"August"},{"Name":"September"},{"Name":"October"},{"Name":"November"},{"Name":"December"},{"Name":"January"}]

Sign up to request clarification or add additional context in comments.

3 Comments

List<Calendar[200]> a list of arrays? Is that what you really intended?
@AaronLS Definitely! :) Thank you.
@Erik Philips Awesome, efficient, complete and pretty answer! thanks a lot :)
-1

Just create a SQL command to get the count as follows:

SqlCommand sqlCommand = new SqlCommand(" SELECT Count (*) FROM table ", myConnection);

int rows = sqlCommand.ExecuteScalar();

Calendar[] loArrayRegistrosCalendario = new Calendar[rows];

4 Comments

I'm confused as to the downvotes here. If he creates his array to the size of the data set then it'll only loop for the correct no of items surely...or am I missing something here?
Perhaps because this adds another call to the DB. Also, what if rows are added or deleted from table between getting the count and selecting the rows?
I'd partly agree with your first point, although I'd argue the overhead would be minimal in this example. However the adding/deletion of rows I can't see being an issue unless it happens in the split second between opening the reader and getting the count.
In my experience, things happen in that split second much more often than one may think. Race conditions can be very difficult to track down and it is best to just avoid creating the possibility of one whenever possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.