Trying to loop through a list of objects using a foreach loop and I’ve come into trouble as I get a compiler error
Foreach statement cannot operate on variable object because it does not contain a definition for
GetEnumerator.
I parse a file to an anonymous List and then use that list in a method.
var list = (from s in File.ReadAllLines(path).Select(a => a.Split(new[] { '|' }, StringSplitOptions.None))
select new
{
Nbr = s[0].Trim(),
Name = s[1].Trim(),
Phone = s[2].Trim(),
Addr = s[3].Trim()
}).ToList();
findmatch(list);
}
Public static void findmatch(object list)
{
foreach(var entry in list)
I also tried to change the code around like this:
foreach(var entry in list.GetType().GetProperties()) as I still get this error
Sorry yes I made an edit to recognize that I’m carrying list over to another method.
Alright, now that you have shown your real code it’s clear where the problem is. Anonymous objects cannot leave the local context. You cannot loop over an instance of an
object. And you cannot use this anonymous object anywhere outside of the context in which this anonymous object is defined in.So start by defining a model:
then adapt your LINQ query to return an IEnumerable of this model instead of some anonymous object:
and finally adapt your
findmatchmethod to take an IEnumerable of your model instead of some weakly typed object which you cannot iterate over anyways: