2010-02-19 25 views
1

我在Windows應用程序中使用了ListBox。我從WCF服務器獲得變量iplist在不使用for循環的情況下從值列表中添加列表框中的值

之後,我在列表框中添加了該列表,但它生成了一個錯誤:「修改了集合,可能無法執行enumuration」。

我該如何解決這個問題?

我的代碼是:

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); 
      } 
     } 
    } 
} 

回答

1

不能添加到一個枚舉,在這種情況下,你的列表框,而你正在遍歷集合。

你可能想是這樣的:

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); 
     } 
    } 
} 
+0

如果(!listBox1.Items.Any(I => String.Compare(i.ToString(),pc.IPAddress,真)== 0)){ 在 此行中我沒有得到Listbox1.Items.Any函數選項... 現在我應該如何添加列表框中的值 – Suryakavitha

+0

您需要添加對System.Linq的引用並將一個using添加到您的代碼單元中。查看更新示例 – James

0

你的問題是什麼詹姆斯說,你不能添加到一個枚舉,而遍歷集合。儘管你也可以用這種方式解決它。 (我假設pc.IPAddress是一個字符串,如果他們是別的東西,只是切換的類型。)

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)); 
    } 
} 
+0

@wasatz,問題說'不使用for循環' – James

+0

廢話!我完全錯過了。好的,在這種情況下,我的代碼完全不相關。對於那個很抱歉。 – wasatz

0

如果你讀你的代碼很可能不是你想要的。 你想添加IP地址列表,如果它不存在的權利?

for (int i = 0; i < listBox1.Items.Count; i++) 
{ 
if (!listBox1.Items[i].ToString().Contains(pc.IPAddress)) 
{ 
    listBox1.Items.Add(pc.IPAddress); 
} 
} 

你現在要做的是循環播放列表框中的項目。如果某個項目不包含ipaddress,則將其添加到列表框中。 你想要的是當它沒有發生整個列表框時添加ipaddress。因此:

//IPAddress is a string? 
if (!listBox1.Items.Contains(pc.IPAddress)) 
{ 
listBox1.Items.Add(pc.IPAddress); 
} 
相關問題