Add value in listbox from list of values without using for loop
I have used a ListBox in my Windows application. I got the variable iplist
from a WCF server.
After that i addded that list in my ListBox, but it generated an error: "Collections modified, enumuration may not execute".
How might I solve this problem?
My code is:
foreach (ClsPC pc in iclsobj.GetPC())
{
if (listBox1.Items.Count == 0)
{
listBox1.Items.Add(pc.IPAddress);
}
else
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
{
listBox1.Items.Add(pc.IPAddress);
}
}
}
}开发者_运维百科
You can't add to an enumeration, in this case your listbox, whilst you are iterating over the collection.
You probably want something like:
using System.Linq;
...
foreach (ClsPC pc in iclsobj.GetPC())
{
if (listBox1.Items.Count == 0)
{
listBox1.Items.Add(pc.IPAddress);
}
else
{
if (!listBox1.Items.Any(i => String.Compare(i.ToString(), pc.IPAddress, true) == 0))
{
listBox1.Items.Add(pc.IPAddress);
}
}
}
Your problem is exactly what james says, you can't add to an enumeration while iterating over the collection. Though you could also solve it in this way. (I'm assuming that pc.IPAddress is a string, if they're something else, just switch the type.)
foreach (ClsPC pc in iclsobj.GetPC())
{
if (listBox1.Items.Count == 0)
{
listBox1.Items.Add(pc.IPAddress);
}
else
{
var toAdd = new List<string>();
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
{
toAdd.Add(pc.IPAddress);
}
}
toAdd.ForEach(item => listBox1.Items.Add(item));
}
}
If you read your code it is probably not what you want. You want to add the IP address to the list if it not exists right?
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (!listBox1.Items[i].ToString().Contains(pc.IPAddress))
{
listBox1.Items.Add(pc.IPAddress);
}
}
What you do now is loop over the items in the listbox. if an item does not contain the ipaddress you will add it to the listbox. What you want is add the ipaddress when it's not occuring the the whole listbox. Therefore:
//IPAddress is a string?
if (!listBox1.Items.Contains(pc.IPAddress))
{
listBox1.Items.Add(pc.IPAddress);
}
精彩评论