Solved

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

Posted on 2006-11-14
6
224 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 63

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

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

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

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

691 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