Create a gist now

Instantly share code, notes, and snippets.

Imperative and Functional coding in C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace HigherOrderFunctions
{
enum Tech
{
Red,
Green,
Blue,
Yellow
}
internal class Skill
{
internal string Name { get; set; }
internal ushort Age { get; set; }
internal Tech Technology { get; set; }
internal ushort Score { get; set; }
}
public class ImperativeFunctional
{
internal static IDictionary<Tech, string> GetAnswerImperative(IEnumerable<Skill> skills)
{
var scoreNames = new Dictionary<Tech, Skill>();
foreach (var skill in skills)
{
if (skill.Age >= 40)
continue;
if (!scoreNames.ContainsKey(skill.Technology) || scoreNames[skill.Technology].Score < skill.Score)
scoreNames[skill.Technology] = skill;
}
var answer = new Dictionary<Tech, string>();
foreach (var keyValue in scoreNames)
answer[keyValue.Key] = keyValue.Value.Name;
return answer;
}
internal static IDictionary<Tech, string> GetAnswerFunctional(IEnumerable<Skill> skills)
{
return skills.
Where(skill => skill.Age < 40).
GroupBy(skill => skill.Technology).
Select(group => new KeyValuePair<Tech, string>(group.Key, group.
OrderByDescending(skill => skill.Score).
Select(skill => skill.Name).
FirstOrDefault())
).
ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
public static void Main(string[] args)
{
var skills = new List<Skill>
{
new Skill { Name = "alice", Age = 24, Technology = Tech.Blue, Score = 86 },
new Skill { Name = "alice", Age = 24, Technology = Tech.Green, Score = 80 },
new Skill { Name = "bob", Age = 20, Technology = Tech.Red, Score = 76 },
new Skill { Name = "bob", Age = 20, Technology = Tech.Green, Score = 68 },
new Skill { Name = "charlie", Age = 45, Technology = Tech.Blue, Score = 96 },
new Skill { Name = "dylan", Age = 32, Technology = Tech.Blue, Score = 75 },
new Skill { Name = "dylan", Age = 32, Technology = Tech.Green, Score = 81 },
new Skill { Name = "dylan", Age = 32, Technology = Tech.Red, Score = 54 },
new Skill { Name = "evelyn", Age = 29, Technology = Tech.Green, Score = 83 },
new Skill { Name = "evelyn", Age = 29, Technology = Tech.Red, Score = 78 },
new Skill { Name = "francis", Age = 19, Technology = Tech.Red, Score = 64 }
};
Console.WriteLine("Imperative Answer: {{{0}}}", string.Join(", ", GetAnswerImperative(skills).Select(kvp => string.Format("{0}: '{1}'", kvp.Key, kvp.Value))));
Console.WriteLine("Functional Answer: {{{0}}}", string.Join(", ", GetAnswerFunctional(skills).Select(kvp => string.Format("{0}: '{1}'", kvp.Key, kvp.Value))));
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment