Created
March 1, 2020 07:16
-
-
Save CDillinger/a902ae79acd4fe9b5fa3055dc0c52d59 to your computer and use it in GitHub Desktop.
Largest Public College Undergrad Count by U.S. Political Division
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace CollegeData | |
{ | |
public class ApiResponse | |
{ | |
[JsonProperty("metadata")] | |
public Metadata Metadata { get; set; } | |
[JsonProperty("results")] | |
public SchoolDetails[] Results { get; set; } | |
} | |
public class Metadata | |
{ | |
[JsonProperty("total")] | |
public int Total { get; set; } | |
[JsonProperty("page")] | |
public int Page { get; set; } | |
[JsonProperty("per_page")] | |
public int PerPage { get; set; } | |
} | |
public class SchoolDetails | |
{ | |
[JsonProperty("school.name")] | |
public string SchoolName { get; set; } | |
[JsonProperty("latest.student.size")] | |
public int LatestUndergradStudentBodySize { get; set; } | |
} | |
class Program | |
{ | |
static ApiResponse GetResponse(int page) | |
{ | |
const string apiKey = "your-data.gov-api-key"; | |
var perPage = 100; | |
var fields = new[] | |
{ | |
"school.name", | |
"latest.student.size" | |
}; | |
const string urlBase = "https://api.data.gov/ed/collegescorecard/v1/schools.json"; | |
var url = $"{urlBase}?sort=latest.student.size:desc&school.ownership=1&fields={string.Join(',', fields)}&per_page={perPage}&page={page}&api_key={apiKey}"; | |
var client = new HttpClient(); | |
var jsonResponse = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result; | |
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse); | |
return apiResponse; | |
} | |
static void Main(string[] args) | |
{ | |
var allDetails = new List<SchoolDetails>(); | |
ApiResponse response = null; | |
for (var page = 0; response == null || response.Results.Length > 0; page++) | |
{ | |
response = GetResponse(page); | |
allDetails.AddRange(response.Results); | |
} | |
var schoolDetailsByState = allDetails.ToLookup(d => d.SchoolState, d => d).OrderByDescending(g => g.ToList().Sum(d => d.LatestUndergradStudentBodySize)).ToDictionary(d => d.Key, d => d.ToList()); | |
ToCsv(schoolDetailsByState); | |
} | |
static void ToCsv(Dictionary<string, List<SchoolDetails>> schoolDetailsByState) | |
{ | |
var sb = new StringBuilder(); | |
foreach (var (state, details) in schoolDetailsByState) | |
{ | |
var largestUndergrad = details.OrderByDescending(d => d.LatestUndergradStudentBodySize).First(); | |
sb.AppendLine($"{state}\t{largestUndergrad.SchoolName}\t{largestUndergrad.LatestUndergradStudentBodySize}"); | |
} | |
var csv = sb.ToString(); | |
File.WriteAllText("file-path", csv); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment