I have created a custom object so that I can save/load data from my Unity game into a Firebase Database. The custom object Result
consists of a list of tuples List<int,int,int)>
.
public class Result
{
public List<(int,int,int)> results;
public Result(List<(int,int,int)> results) {
this.results = results;
}
// get a list of one of the tuple items
public List<int> getList(int id) {
List<int> singlResults = new List<int>();
// loop through each tuple
foreach (var item in this) { //error here
// do something
}
}
}
However when I try to loop over the List in the Result
object I get an error:
foreach statement cannot operate on variables of type ‘Result’ because ‘Result’ does not contain a public instance definition for ‘GetEnumerator’
3
Answers
Your
Result
class must implementIEnumerable
andIEnumerator
to iterate using theforeach
loop.here you will find the details.
Based on the your code, the error seems to be occurring because the Result class is not implementing the IEnumerable interface (which is required for the foreach loop to work) OR doesn’t contain a method called GetEnumerator() that the interface requires.
The IEnumerable interface in C# provides the basic functionality required to allow an object to be enumerated using a foreach loop.
You would want your code to look something like this:
Your
Result
itself actually doesn’t and doesn’t need to implementIEnumerable
at all as suggested by others. That’s overcomplicating it a bit imhoAll you need to do is instead of trying to iterate
this
rather iterate theresults
and doCould also go through
Linq
if you want and do