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