简体   繁体   English

C#从外部范围访问数据表

[英]C# Access datatable from outer scope

I have JSON files with 2 objects... for this example "Country" and "Data". 我有2个对象的JSON文件...对于此示例“国家”和“数据”。 I'm trying to deserialize the "Data" object into datatable "sortedFileData" but have been unable to access the datatable from inside the while loop. 我正在尝试将“数据”对象反序列化为数据表“ sortedFileData”,但无法从while循环内部访问数据表。 I've found how to solve if creating a new class ( C#: access variable in the inner scope from the outer scope ) but I won't be doing that here. 我已经找到了如何解决是否创建一个新类的方法( C#:从外部作用域到内部作用域的访问变量 ),但是在这里我不会这样做。

        using (FileStream fs = new FileStream(selectedProject, FileMode.Open, FileAccess.Read))
        using (StreamReader sr = new StreamReader(fs))
        using (JsonTextReader reader = new JsonTextReader(sr))
        {
            DataTable sortedFileData = new DataTable();
            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.StartObject)
                {
                    // Load each object from the stream and do something with it
                    JObject obj = JObject.Load(reader);
                    System.Windows.MessageBox.Show((string)obj["Country"]);
                    DataTable sortedFileData = JsonConvert.DeserializeObject<DataTable>((string)obj["Data"]);
                }
            }
        }

        string sorted = "Name ASC, Age ASC, Date ASC";
        DataView dtView = new DataView(sortedFileData) {Sort = sorted};

Sample JSON: 样本JSON:

  { "Country": "England", "Data": [ { "Name": "Bill", "Age": "70", "Date": "2015-05-27" }, { "Name": "Sara", "Age": "36", "Date": "2015-01-21" }, { "Name": "Bob", "Age": "7", "Date": "2011-05-24" } ] } 

You can declare it outside of the loops and assign it in the same place. 您可以在循环外部声明它,并将其分配在同一位置。

    DataTable sortedFileData;

    using (FileStream fs = new FileStream(selectedProject, FileMode.Open, FileAccess.Read))
    using (StreamReader sr = new StreamReader(fs))
    using (JsonTextReader reader = new JsonTextReader(sr))
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.StartObject)
            {
                // Load each object from the stream and do something with it
                JObject obj = JObject.Load(reader);
                System.Windows.MessageBox.Show((string)obj["Country"]);
                sortedFileData = JsonConvert.DeserializeObject<DataTable>((string)obj["DataTable1"]);
            }
        }
    }

    string sorted = "Name ASC, Age ASC, Date ASC";
    if (sortedFileData != null) 
    {
        DataView dtView = new DataView(sortedFileData) {Sort = sorted};
    }

And then you can just do a quick null check to make sure that everything went as expected. 然后,您可以进行快速的空检查以确保一切都按预期进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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