Solved

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

Posted on 2006-11-14
6
219 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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now