ForEach 可观察集合中的错误

ForEach error in a observablecollection

我对 observable 集合中的 ForEach 有疑问。 Visual Studio 告诉我:

"The 'observablecollection' does not contain a 'ForEach' definition and was not found at the 'ForEach' extension method that accepts a first 'observablecollection' type argument. Probably missing a directive using or reference to the assembly"

问题是,类似的代码在另一个项目中工作正常,但在这个新项目中却不行。我哪里错了?

谢谢

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

ObservableCollection 没有 ForEach 方法。

我怀疑您可能会想到 ListForEach - 但 List 是不同的类型。

我会考虑使用 foreach 循环,或者在使用 ForEach 之前调用 ToList