1

我在可觀察集合中遇到ForEach問題。 Visual Studio告訴我:ForEach在observablecollection中的錯誤

「'observablecollection'不包含'ForEach'定義,並且沒有在'ForEach'擴展方法中找到,它接受第一個'observablecollection'類型參數。可能缺少使用or的指令參考大會「

問題是,在另一個項目中的類似代碼工作正常,但在這個新項目中沒有。我錯在哪裏?

謝謝

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ProvaBindingXaml 
{ 
    /* public class Impiegato 
    { 

     public string Nome { get; set; } 
     public string Cognome { get; set; } 
     public string Matricola { get; set; } 

    } 
    */ 

    public class Rule 
    { 
     public string Ruolo { get; set; } 

     public Rule(string ruolo) 
     { 
      this.Ruolo = ruolo; 
     } 

     public override string ToString() 
     { 
      return this.Ruolo; 
     } 

     public static ObservableCollection<Rule> GetAllRules() 
     { 
      var CollectionRuoli = new ObservableCollection<Rule>(); 
      CollectionRuoli.Add(new Rule ("Impiegato")); 
      CollectionRuoli.Add(new Rule ("Dirigente")); 
      CollectionRuoli.Add(new Rule ("Operaio")); 
      CollectionRuoli.Add(new Rule ("Manutentore")); 
      CollectionRuoli.Add(new Rule ("Presidente")); 
      return CollectionRuoli; 

     } 


     public static void GetComboBoxList(ObservableCollection<Rule> RuleItems) 
     { 
      var allItems = GetAllRules(); 
      RuleItems.Clear(); 
      allItems.ForEach(p => RuleItems.Add(p)); 
     } 
    } 
} 
+0

也許幫助:https://stackoverflow.com/a/2519433/316799 –

回答

0

ObservableCollection沒有ForEach方法。

我懷疑你可能會想到ListForEach - 但List是一個不同的類型。

我會考慮使用foreach循環,或在使用ForEach之前調用ToList

+0

好的,但爲什麼這個代碼,它是在另一個項目,工作? https://s13.postimg.org/rhyiw3vkn/Immagine.png – raffux3

+1

在其他項目中,轉到ForEach行,右鍵單擊和執行。我的猜測是有人在那裏寫了一個擴展方法,但是你需要檢查並向我們確認。 – mjwills

+0

是:有這個代碼 '命名空間WinRTXamlToolkit.Tools { 公共靜態類EnumerableExtensions { 公共靜態無效的ForEach (這IEnumerable的名單,行動動作); public static List Shuffle (此IEnumerable 列表); } }' 哦,我想我明白了!謝謝 – raffux3