遍历类列表

时间:2020-04-16 13:30:01

标签: c# .net json

我从文本文件中列出了“团队”列表。我只是无法遍历它

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循环:

foreach (var item in LeagueTeams)
{

}

但是LeagueTeams中的foreach出错

在那种情况下不存在。

整个代码段:

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)
        {

        }
    }
}

2 个答案:

答案 0 :(得分:4)

您正试图在声明的范围之外访问leagueTeams,这就是为什么出现此错误的原因。因此,您需要在List<Teams> leagueTeams语句之前移动using的声明:

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

此外,您还需要在foreach循环中修复变量的名称。根据您的声明,LeagueTeams不正确,应该为leagueTeams

foreach (var item in leagueTeams)

答案 1 :(得分:1)

您可能正在尝试遍历LeagueTeams类,您可能想做的是通过反序列化(解析)文件来遍历刚创建的列表。

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