ChunkyFresh
ChunkyFresh

Reputation: 65

C# Count if Field Exists

Below is a script making an API call which retrieves some ReportIDs (from a database table), passes them through a method which will run them individually, and finally see if each contains the field, Name_First.

What I need help with is creating a count that will tell me how many reports contain the field Name_First, how many don't, and what's the percentage out of all reports having the field, Name_First.

Currently, the script queries two ReportIDs (12300,12301) for testing. One report has the field Name_First in it and the other one doesn't. From the foreach loop I've written, I'm aiming to count every time there is a null and every time there isn't, get a total, and just divide the not null count by the sum of both. However, when I run this script, the console at

                Console.WriteLine(total);
                Console.WriteLine(total_noFirstName);
                Console.WriteLine(total_FirstName);

returns values of 0, 0, and 0. I think I'm having a scope issue here, but I'm not really sure. If I could receive some help solving this, I'd very much appreciate it.

Thank you!


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace NameFirstSearch
{
   class Program
{

    static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

        const string username = "Username";
        const string password = "Password";



        const string baseUrl = "https://test.com/rest/services/";


        const string queryString = "query?q=Select * From Report Where ReportID in (12300,12301)";
        const string queryNameFirst = "getreport/";

        var client = new HttpClient();

        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var auth = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);

        //GetReports(client, queryString).Wait();
        var  reportsList = GetReports(client, queryString).Result;
        GetNameFirst(client, queryNameFirst, reportsList).Wait();

        Console.ReadLine();

    }



    static async Task<List<Properties>> GetReports(HttpClient client, string queryString)
    {

        List<Properties> result = new List<Properties>();

        var response = await client.GetAsync(queryString);

        // Check for a successfull result
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject<List<Properties>>(json);
        }
        else
        {
            // Error code returned
            Console.WriteLine("No records found on first method.");
        }

        return result;

    }


    static async Task GetNameFirst(HttpClient client, string queryNameFirst, List<Properties> results)
    {
        string reportType = ".json";

        foreach (var item in results)
        {
            var output = await client.GetAsync(queryNameFirst + item.ReportID + reportType);


            if (output.IsSuccessStatusCode)
            {
                var allText = await output.Content.ReadAsStringAsync();

                var fields = JsonConvert.DeserializeObject<List<FirstName>>(allText);

                var test = JsonConvert.SerializeObject(fields);

                Console.WriteLine(test);

                int total_FirstName = 0;
                int total_noFirstName = 0;
                int total = total_FirstName + total_noFirstName;
                foreach (var split in fields)
                {

                    if (split.Name_First != null)
                    {
                        total_FirstName++;

                    }
                    else if (split.Name_First == null)
                    {

                        total_noFirstName++;

                    }

                }
                Console.WriteLine(total);
                Console.WriteLine(total_noFirstName);
                Console.WriteLine(total_FirstName);

            }
            else
            {
                // Error code returned
                Console.WriteLine("No records found on second method.");
            }

        }

    }



}
}

Class Properties

int ReportID {get; set;}

Class FirstName

string Name_First {get; set;}

Results at Console.WriteLine(test);

 [{"Name_First":"Mario"}]
 [{"Name_First":null}]

Results for Console.WriteLine(allText);

 [{"Name_First":"Mario","Entry_ID":"72313"}]
 [{"Name_Last":"Rincon Recio","Entry_ID":"72313"}]

Upvotes: 0

Views: 303

Answers (1)

iakobski
iakobski

Reputation: 1274

If you want to keep a count of things in a loop, you need to declare the counter variables outside of the loop, otherwise they get reinitialised. Using your data from the question, the relevant loop should look like this:

    List<string> allTexts = new List<string>
    { @"[{""Name_First"":""Mario"",""Entry_ID"":""72313""}]",
      @"[{""Name_Last"":""Rincon Recio"",""Entry_ID"":""72313""}]" };

    int total_FirstName = 0;
    int total_noFirstName = 0;

    foreach(var allText in allTexts)
    {
        var fields = JsonConvert.DeserializeObject<List<FirstName>>(allText);
        var test = JsonConvert.SerializeObject(fields);
        Console.WriteLine(test);

        foreach (var split in fields)
        {
            if (split.Name_First != null)
            {
                total_FirstName++;
            }
            else
            {
                total_noFirstName++;
            }
        }
    }
    int total = total_FirstName + total_noFirstName;
    Console.WriteLine(total);
    Console.WriteLine(total_noFirstName);
    Console.WriteLine(total_FirstName);

Output:

 [{"Name_First":"Mario"}]
 [{"Name_First":null}]
 2
 1
 1

Upvotes: 1

Related Questions