Solved

how do I create and iterate through a array of structures?

Posted on 2006-11-14
6
221 Views
Last Modified: 2010-04-16
I am going through a loop reading from a database and I want to populate a structure and append it to an array, then iterate through the array in another loop.

 struct emailInfo {
  public int emailBlastID;
  public string subject;
  public string image;
  public string link;
  public string body;
  public string emailAddress;
  public string memberID;
  public long emailSentID;  
}

Can someone give me some sample code of the best way to do this?

Thanks,

John

0
Comment
Question by:jbrahy
6 Comments
 
LVL 1

Author Comment

by:jbrahy
ID: 17941271
This is what I have so far.


      public EmailInfo[] ProcessEmailQueue() {
         int counter = 0;
         DateTime startTime = DateTime.Now;
         EmailInfo[] emailInfoArray = new EmailInfo();

         using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
            using (SqlCommand sqlCommand = new SqlCommand()) {
               try {
                  sqlCommand.Connection = sqlConnection;
                  sqlCommand.CommandType = CommandType.StoredProcedure;
                  sqlCommand.CommandText = "GetPendingEmailData";
                  sqlConnection.Open();

                  using (SqlDataReader reader = sqlCommand.ExecuteReader()) {
                     while (reader.Read()) {
                        EmailInfo emailInfo = new EmailInfo();
                        emailInfo.emailBlastID = Convert.ToInt32(reader["emailBlastID"].ToString());
                        emailInfo.subject = reader["subject"].ToString();
                        emailInfo.image = reader["image"].ToString();
                        emailInfo.link = reader["link"].ToString();
                        emailInfo.body = reader["body"].ToString();
                        emailInfo.emailAddress = reader["emailAddress"].ToString();
                        emailInfo.memberID = reader["memberID"].ToString();
                        emailInfo.emailSentID = Convert.ToInt64(reader["emailSentID"].ToString());
                        emailInfoArray[counter] = emailInfo;
                        counter++;
                     }
                  }
                  TimeSpan duration = DateTime.Now - startTime;
                  HandleInfo("Retrieved " + counter.ToString() + " emails in " + duration);
               } catch (Exception ex) {
                  HandleError("Exception in ProcessEmailQueue: " + ex.Message + " -- " + ex.Source + " == " + ex.StackTrace);
               }
            }
         }
         return emailInfoArray;
      }


      void SendEmails(EmailInfo[] emailInfoArray) {
         long counter = 0;
         foreach (EmailInfo emailInfo in emailInfoArray) {
            counter++;
            string message = email.generateEmail(emailInfo.emailBlastID, emailInfo.memberID, emailInfo.subject, emailInfo.image, emailInfo.link, emailInfo.body);
            string result = sendEmail(emailFromAddress, emailInfo.emailAddress, emailInfo.subject, message);
            Sleep();

            if (result.Length > 0) {
               HandleError("Error sending to: " + emailInfo.emailAddress + " : Error details: " + result);
            } else {
               using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
                  using (SqlCommand sqlCommand = new SqlCommand()) {
                     sqlConnection.Open();
                     sqlCommand.Connection = sqlConnection;
                     sqlCommand.CommandType = CommandType.StoredProcedure;
                     sqlCommand.CommandText = "SetEmailAsSent";
                     sqlCommand.Parameters.Add("@emailSentID", SqlDbType.BigInt).Value = emailInfo.emailSentID;
                     sqlCommand.ExecuteNonQuery();
                  }
               }
            }
         }
      }
0
 
LVL 13

Accepted Solution

by:
joechina earned 500 total points
ID: 17941301
In .NET 2.0

You can define a List of emailInfo

List<emailInfo> ls = new List<emailInfo>();

You can add emailInfo instance to the list
(create and assign value to aEmailInfo)
ls.Add(aEmailInfo);

To do a loop

foreach(emailInfo e in ls)
{
....
}

0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17941317
You can't append to an array unless you know the number of elements you need before hand and can size the array in advance.
If you are reading from a database and are gettinmg the data fro teh struct from rows in a tbale then you8 can size the array based on the rows in the table.
If not use an ArrayList.

DataSet data;

// populate your dataset with data
// I will assume that the data is in a single table and that the column names of the table are the same as the fields of the struct.

emailInfo[] emails = new emailInfo[dataset.tables[0].Rows.Count];

for (int i = 0; i < dataset.tables[0].Rows; i++){
     DataRow row = dataset.tables[0].Rows[i];
     emailInfo e = new emailInfo();
     e.emailBlastID = (int)row["emailBlastID"];
     e.subject = (int)row["subject"];
     e.image = (int)row["image"];
     e.link = (int)row["link"];
     e.body = (int)row["body"];
     e.emailAddress = (int)row["emailAddress"];
     e.memberID = (int)row["memberID"];
     e.emailSentID = (int)row["emailSentID"];  
     emails[i] = e;
}

Now you have an array of emailInfo Structs you can loop through :

foreach (emailInfo email in emails){
    // do your thing
}
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 13

Expert Comment

by:joechina
ID: 17941360
Modify the lines
from
EmailInfo[] emailInfoArray = new EmailInfo();
to
List<EmailInfo> emailInfoArray = new List<EmailInfo>();
(ArrayList emailInfoArray = new ArrayList(); //if .net 1.1)

from
emailInfoArray[counter] = emailInfo;
to
emailInfoArray.Add(emailInfo);
(same in .net 1.1)

from
return emailInfoArray;
to
return emailInfoArray.ToArray()
(return (EmailInfo[])emailInfoArray.ToArray();//if .net 1.1)

0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 17941482
       struct emailInfo
        {
            public int emailBlastID;
            public string subject;
            public string image;
            public string link;
            public string body;
            public string emailAddress;
            public string memberID;
            public long emailSentID;
        }

        private ArrayList emailInfoArray;

        private void button1_Click(object sender, EventArgs e)
        {
            // Add data to array
            emailInfoArray = new ArrayList();
            emailInfo myEmailInfo = new emailInfo();
            myEmailInfo.emailBlastID = 1;
            myEmailInfo.subject = "Add Structure to ArrayList";
            myEmailInfo.image = "Image";
            myEmailInfo.link = "http://www.expers-exchange.com";
            myEmailInfo.body = "This is the body";
            myEmailInfo.emailAddress = "MyEmail@mydomain.com";
            myEmailInfo.memberID = "123";
            myEmailInfo.emailSentID = 123456;
            emailInfoArray.Add(myEmailInfo);

            myEmailInfo = new emailInfo();
            myEmailInfo.emailBlastID = 2;
            myEmailInfo.subject = "Add second Structure to ArrayList";
            myEmailInfo.image = "Image 2";
            myEmailInfo.link = "http://www.expers-exchange.com";
            myEmailInfo.body = "This is the body for item 2";
            myEmailInfo.emailAddress = "MyEmail@mydomain.com";
            myEmailInfo.memberID = "456";
            myEmailInfo.emailSentID = 654321;
            emailInfoArray.Add(myEmailInfo);

            // Write the data out to the console from the array list
            for (int idx = 0; idx < emailInfoArray.Count; idx++)
            {
                emailInfo eInfo = (emailInfo)emailInfoArray[idx];
                Console.WriteLine("E-mai Number " + idx.ToString());
                Console.WriteLine(eInfo.emailBlastID.ToString());
                Console.WriteLine(eInfo.image);
                Console.WriteLine(eInfo.link);
                Console.WriteLine(eInfo.body);
                Console.WriteLine(eInfo.emailAddress);
                Console.WriteLine(eInfo.memberID);
                Console.WriteLine(eInfo.emailSentID.ToString());
                Console.WriteLine();
            }
        }


Fernando
0
 
LVL 1

Author Comment

by:jbrahy
ID: 17943401
Thank you everyone for all your input, but I didn't need to go past the first post to solve it. I would have split the points between you all but I don't believe it would have been fair to joechina.

Thanks again
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question