Solved

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

Posted on 2006-11-14
6
220 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Different Delete Messages 7 37
C# Json POSt to Rest API 4 37
SQL Query Producing decimal places when it shouldn;t be 8 35
Web Form VB.Net  import CSV 4 26
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
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…

920 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

15 Experts available now in Live!

Get 1:1 Help Now