-2

There are List<IClient> and List<ClientName> When the new Client connect to Service(Server), a new client's name will be written to all clients who is in the session. But new client get only yourself. I have:

foreach (IClientCallBack client in listClientCallBacks)
{
    if (client == listClientCallBacks.Last())
    {
        foreach (var n in listClientsName)
        {
            client.Enter(n);
        }
        return;
    }

    client.Enter(name);
}

Please prompt are there variants without if in this case? Thanks in advance. PS:Sorry for my English Language level.

Hamid Pourjam
  • 18,954
  • 8
  • 53
  • 67

2 Answers2

0

If you really want to remove that if you could write two separate loops (that doesn't mean that you have a significant decrease in performance because also your code executes two loops) and yes, if I have guessed your intention correctly, using this logic is more clear.

// Get directly the last one and add the clients name already in the 'session'
// to this element. I suppose that the last one need to be informed of the
// clients already in the list.....
IClientCallBack client in listClientCallBacks.Last();
foreach (var n in listClientsName)
    client.Enter(n);

// Now for every client in the session EXCLUDING  the last one 
// inform them of the new client that has joined your 'session'
foreach (IClientCallBack client in listClientCallBacks.Take(listClientCallBacks.Length - 2))
    client.Enter(name);
Steve
  • 203,265
  • 19
  • 210
  • 265
0

The foreach loop can be very useful, but there are cases when the good old for loop has its advantage too. Examples are when you are not processing every item of a collection, or if you need the index of the current element.

If I understood your problem correctly, you want a special handling of the last element:

// first until second last element
int secondLastIndex = listClientCallBacks.Count - 2;
for (int index = 0; index <= secondLastIndex; index++)
{
    IClientCallBack client = listClientCallBacks[index];
    client.Enter(name);
}

// last element
if (listClientCallBacks.Count > 0)
{
    IClientCallBack lastClient = listClientCallBacks.Last();
    foreach (var n in listClientsName)
    {
        lastClient.Enter(n);
    }
    return;
}
martinstoeckli
  • 21,405
  • 4
  • 52
  • 78