Skip to content

Instantly share code, notes, and snippets.

@doodlehaus
Last active April 16, 2021 16:22
Show Gist options
  • Save doodlehaus/88c39c42129dbeacc5c212cd17e08b9d to your computer and use it in GitHub Desktop.
Save doodlehaus/88c39c42129dbeacc5c212cd17e08b9d to your computer and use it in GitHub Desktop.
Sorting Bikes with Linq
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace popular_bikes
{
class Program
{
static void Main(string[] args)
{
// Call and parse json from endpoint
String url = "https://trekhiringassignments.blob.core.windows.net/interview/bikes.json";
System.Net.WebClient client = new System.Net.WebClient();
String json = client.DownloadString(url);
// Grab the array of bikes from each child to generate an array of arrays
var bikesList = JArray.Parse(json).Children().Select(b => b["bikes"]).ToArray();
List<String> stringifiedBikeList = new List<String>();
// generate a new list where I sort and join each list of bikes
foreach(var bikes in bikesList) {
var sortedBikesList = bikes.ToObject<List<string>>();
sortedBikesList.Sort();
var key = String.Join(",", sortedBikesList);
stringifiedBikeList.Add(String.Join(",", sortedBikesList));
}
// use LINQ to query, order and count the stringified members of the list
var topTwenty = (from b in stringifiedBikeList
group b by b
into g
orderby g.Count() descending
select new { Bikes = g.Key, Count = g.Count() }).Take(20);
// output results
foreach(var b in topTwenty) {
Console.WriteLine(b.Count + ": " + b.Bikes);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment