0

I want to loop through a collection of servers and ports (3 of each to be exact) and try to make a connection, once a connection is made I can move on with the rest of the code.. here is what i have.

        IRC_SETTINGS IRC; //3 servers & 3 ports.
        foreach (string SERVER in IRC.IRC_SERVERS)
        {
            try
            {
                ircSocket = new TcpClient(SERVER, PORT);
                break; //;when we have a working connection.
            }
            catch(Exception){}
        }

I guess that works fine for the servers part, but how do I go about looping through the ports at the same time? something like foreach (string server, int port in ....

ace007
  • 577
  • 1
  • 10
  • 20

1 Answers1

1

You can put them into single data structure (e.g. list) and them loop through them:

public class IrcServer
{
    public string Name { get; set; }
    public int Port { get; set; }

    // perhaps some methods
}

IList<IrcServer> servers = new List<IrcServer>();

foreach(IrcServer server in servers)
{
    // server.Name, server.Port
}

Update

Since you have two different arrays (one for server names and one for port numbers) you can merge them using into dictionary:

int[] ports = { 1, 2, 3 };
string[] servers = { "one", "two", "three" };

var serversWithPorts = servers.
    Zip(ports, (s, i) => new { s, i }).
    ToDictionary(i=> i.s, i => i.i);

foreach(var server in serversWithPorts)
{
    Console.WriteLine(server.Key + ":" + server.Value);
}
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • dumb question but then where do I define the servers and ports? :/ I have already a class with a string array of servers and an int array of ports... – ace007 Oct 28 '12 at 10:20
  • So you have two different arrays and you don't want to make single structore out of it? – Zbigniew Oct 28 '12 at 10:21
  • I've edited my question, also take a look at [this SO question](http://stackoverflow.com/questions/6133362/how-to-unifiy-two-arrays-in-a-dictionary) – Zbigniew Oct 28 '12 at 10:27
  • just decided to go with this ircSocket = new TcpClient(IRC.IRC_SERVERS[i], IRC.IRC_PORTS[i]); and increase "i" if there's a connection error. seems to work.. – ace007 Oct 28 '12 at 10:28
  • No problem, I thought about using loop counter (`i`), but I assumed that you would rather use one structure instead of two arrays, so I assumed further that your problem was more like: how to tie togheter two arrays. – Zbigniew Oct 28 '12 at 10:34