Skip to content

Instantly share code, notes, and snippets.

@hurricanepkt
Last active August 29, 2015 14:13
Show Gist options
  • Save hurricanepkt/0ab3d8c9042bea661e73 to your computer and use it in GitHub Desktop.
Save hurricanepkt/0ab3d8c9042bea661e73 to your computer and use it in GitHub Desktop.
Saving Code
Expression<Func<string,string>> upperer = lower => lower.ToUpper();
Console.WriteLine(upperer.ToString());
lower => lower.ToUpper()
using System;
using System.Collections.Generic;
using System.Linq;
namespace SavingCode
{
public static class EnumerableExtension
{
public static T PickRandom<T>(this IEnumerable<T> source)
{
return source.PickRandom(1).Single();
}
public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
{
return source.Shuffle().Take(count);
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.OrderBy(x => Guid.NewGuid());
}
}
}
private static Func<DateTime, string> FindExpression(ClassForPersistance fromDb)
{
return Expressions
.Where(expression1 => fromDb.Code == expression1.ToString())
.Select(expression1 => expression1.Compile())
.First();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace SavingCode
{
class Program
{
private static readonly List<Expression<Func<DateTime, string>>> Expressions = new List<Expression<Func<DateTime, string>>>
{
text => text.Date.ToString("dd MMMM yyyy"),
futureLongDate => futureLongDate.Date.AddDays(4).ToLongDateString()
};
static void Main()
{
//GET AN EXPRESSION
var expression = Expressions.PickRandom();
//WRAP IT FOR PERSISTANCE
var useclass = new ClassForPersistance(expression);
//PERSIST IT
Repo.Save(useclass);
//NEW RETRIEVAL
var fromDb = Repo.First();
//GET THE EXPRESSION FROM THE STORED DATA
var found = FindExpression(fromDb);
//EXECUTE
Console.Write(found.Invoke(new DateTime(1970, 1, 1)));
}
private static Func<DateTime, string> FindExpression(ClassForPersistance fromDb)
{
return Expressions
.Where(expression1 => fromDb.Code == expression1.ToString())
.Select(expression1 => expression1.Compile())
.First();
}
}
public class ClassForPersistance
{
public ClassForPersistance(Expression<Func<DateTime, string>> expression)
{
Code = expression.ToString();
}
public string Code { get; set; }
}
}
namespace SavingCode
{
public class Repo
{
private static ClassForPersistance _classForPersistance;
public static void Save(ClassForPersistance useclass)
{
_classForPersistance = useclass;
}
public static ClassForPersistance First()
{
return _classForPersistance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment