How to deconstruct multiple nested lists in C#

49 Views Asked by At

I am pulling data from an API and the results are in very confusing list has some nested lists in it. My overall goal to have the code output a .csv file that has Unit, Tag, DateTime, and Value on each line. I figured out the first list, but the other embedded ones are out of my depth. The data returned is in a list called tagResult which has a list called value. In the value list it has Tagname (that I want) and list called values. the values list has the timestamp and the actual value I want. Attached is a screenshot from a break point.

Data Structure

Here is my current code.

namespace ConsoleApp7
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Numerics;
    using System.Threading.Tasks;
    using CSharpFunctionalExtensions;
    using CsvHelper;
    using Microsoft.IdentityModel.Tokens;
    using Newtonsoft.Json.Linq;
    using Scada.OneView.Api.Client;
    using Scada.OneView.Api.Client.Abstractions;
    using Scada.OneView.Api.Client.Models.HistData;
    using Serilog;
    class Program
    {
        static async Task Main(string[] args)
        {
            // Initialize parameters
            const string oneViewUrl = "http://192.168.1.11/oneview4";
            const string authenticationUrl = "http://192.168.1.11/oneview4/auth/";
            const string username = "XXX";
            const string password = "SXXXXX";
            const string logFilePath = @"C:\Users\jzala\Documents\PivotGenPy\test7.txt";

            // Initialize logger
            Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File(logFilePath)
            .CreateLogger();

            // Put OneView Authentication URL and username/password here
            var authenticationSettings = new OneViewAuthenticationSettings
            {
                AuthUrl = authenticationUrl,
                Username = username,
                Password = password,
                AuthenticationType = AuthenticationType.IdentityAuthentication,
            };

            // Put OneView URL here
            var oneviewSettings = new OneViewClientSettings
            {
                OneViewUrl = oneViewUrl
            };

            // Create single factory for one OneView, using oneview and authentication settings
            using var oneviewClientFactory = new OneViewClientFactory(
            oneviewSettings,
            authenticationSettings,
            Log.Logger);


            //Historical Values
            var unitGuid = new Guid("d6f49127-d710-4730-9aa1-d44846fd5537");
            var tags = new List<string>() { "WCNV.GriA2_10m_Max", "WCNV.GriA2_10m_Min", "WCNV.GriA2_10m_Std" };
            var dateFrom = new DateTime(2024, 3, 1, 10, 0, 0);
            var DateTO = new DateTime(2024, 3, 5, 0, 0, 0);
            const byte amountOfEvents = 90;


            IOneViewClient oneViewClient = oneviewClientFactory.CreateInstance();

            Result<IReadOnlyList<HistValueResponseDto>> tagResult = await oneViewClient.GetHistTagsAsync(unitGuid, tags, dateFrom,
                DateTO, 2, 2);


            if (tagResult.IsFailure)
            {
                // An error occured
                //Log.Logger.Error(tagResults.Error);
                return;
            }

            // Path of output CSV File
            string csvFilePath = @"C:\Users\jzala\Documents\PivotGenPy\test17.txt";

            using (StreamWriter sw = new StreamWriter(csvFilePath))
            {
                sw.WriteLine("Tags,Count");
                sw.WriteLine(tagResult);

                // Iterates over the results and writes them into the file
               foreach (var d in tagResult.Value.ToList())
                {
                    //Assuming d.Value is a string and d.Count is an int
                    //sw.WriteLine($"{d.Value},{d.Count");
                    sw.WriteLine(d.TagName);
                }

                var test = tagResult.Value.ToList();
              

                //Log.Logger.Information("Historical events from OneView");
                tagResult.Value.ToList().ForEach(Value =>
                Log.Logger.Information("{@Unit},{@Tagname},{@DTTM},{@Value}",Value.TagName,Value.Values.ToList()));
                // Log.Logger.Information("Finish reading");
            }
        }
    }
}

1

There are 1 best solutions below

1
Jon Z On

One of my buddies who runs software engineering at XM helped me out last night. So here is the answer to how to unstack a nested list in an array and in a list.

        var dateFrom = new DateTime(2024, 3, 1, 0, 0, 0);
    var DateTO = new DateTime(2024, 3, 11, 0, 0, 0);
    const byte amountOfEvents = 90;
    IOneViewClient oneViewClient = oneviewClientFactory.CreateInstance();
    Result<IReadOnlyList<HistValueResponseDto>> tagResult = await oneViewClient.GetHistTagsAsync(unitGuid, tags, dateFrom,
        DateTO, 10, 0);
    if (tagResult.IsFailure)
    {
        // An error occured
        Log.Logger.Error(tagResult.Error);
        return;
    }
    //Log.Logger.Information("Historical events from OneView");
    tagResult.Value.ToList().ForEach(Value =>
        Value.Values.ToList().ForEach(Values =>
       Log.Logger.Information("{@Unit},{@tagname},{@Timestamp},{@Value}", unitGuid, Value.TagName, Values.Timestamp, Values.Value)));
}
Log.Logger.Information("done");

}