1

I have a problem with the ForEach in an observablecollection. Visual Studio tells me:

"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".

The problem is that, the similar code in another project, works fine but in this new project not. Where am I wrong?

Thank you

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));
        }
    }
}
raffux3
  • 13
  • 6

1 Answers1

0

ObservableCollection does not have a ForEach method.

I suspect you may be thinking of List's ForEach - but List is a different type.

I would consider using a foreach loop, or call ToList before using ForEach.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • ok but why this code, that it is in another project, works? https://s13.postimg.org/rhyiw3vkn/Immagine.png – raffux3 Jul 14 '17 at 12:50
  • 1
    In that other project, go to the `ForEach` line and right click and `Go To Implementation`. My guess is someone has written an extension method there, but you'd need to check and confirm to us. – mjwills Jul 14 '17 at 12:52
  • yes: there is this code `namespace WinRTXamlToolkit.Tools { public static class EnumerableExtensions { public static void ForEach(this IEnumerable list, Action action); public static List Shuffle(this IEnumerable list); } }` Oh, I think that I understood!!! Thank you – raffux3 Jul 14 '17 at 12:54
  • Well, that is why it works there and not in yours. Also check the links that myself and Felipe have provided against your original post. – mjwills Jul 14 '17 at 12:55