简体   繁体   中英

Iterating through a list of a class

I have made a list of "Teams" from a text file. I am just unable to iterate through it

using(StreamReader sr = new StreamReader("TXT1.txt"))
{
    using(JsonReader jr = new JsonTextReader(sr))
    {
        JsonSerializer js = new JsonSerializer();
        List<Teams> leagueTeams = js.Deserialize<List<Teams>>(jr);
    }
}

This is where the list is made. I tried to do a foreach loop here:

foreach (var item in LeagueTeams)
{

}

But there is an error with the LeagueTeams in the foreach saying

it doesn't exist in that context.

Whole piece of code:

class Teams
{
    public string name;
    public int GoalDiff;
    public int POints;
}
class Program
{
    static void Main(string[] args)
    {
        using(StreamReader sr = new StreamReader("TXT1.txt"))
        {
            using(JsonReader jr = new JsonTextReader(sr))
            {
                JsonSerializer js = new JsonSerializer();
                List<Teams> leagueTeams = js.Deserialize<List<Teams>>(jr);
            }
        }

        foreach (var item in LeagueTeams)
        {

        }
    }
}

You are trying to access the leagueTeams outside the scope of it's declaration, that's why you are getting this error. So what you need is moving the declaration of List<Teams> leagueTeams before your using statement:

List<Teams> leagueTeams = new List<Teams>();
using(StreamReader sr = new StreamReader("TXT1.txt"))
{
   ....
   ....
   leagueTeams = js.Deserialize<List<Teams>>(jr);

Also you need to fix the variable's name in your foreach loop. Based on what you've declared, the LeagueTeams is incorrect and it should be leagueTeams :

foreach (var item in leagueTeams)

You are trying to iterate over LeagueTeams class probably, what you probably want to do is to iterate over the list you have just created by deserializing (parsing) your file.

class Program
{
    static void Main(string[] args)
    {
        List<Teams> leagueTeams = new List<Teams>();
        using(StreamReader sr = new StreamReader("TXT1.txt"))
        {
            using(JsonReader jr = new JsonTextReader(sr))
            {
                JsonSerializer js = new JsonSerializer();
                leagueTeams = js.Deserialize<List<Teams>>(jr);
            }
        }

        foreach (var team in leagueTeams)
        {
            // access each team by 'team' variable
        }

        // another way using LINQ
        leagueTeams.ForEach(team => 
        {
            // access each team by 'team' variable
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM