Skip to content

Instantly share code, notes, and snippets.

@philchuang
Created March 28, 2012 18:54
Show Gist options
  • Save philchuang/2229415 to your computer and use it in GitHub Desktop.
Save philchuang/2229415 to your computer and use it in GitHub Desktop.
Simple object conversion extension method
public static class Program
{
public static void Main (params String[] args)
{
// setup
var dict = new Dictionary<int, String> ();
dict[1] = "The Quick Brown";
dict[2] = "Fox Jumped";
dict[3] = "Over The";
dict[4] = "Lazy Dogs";
// don't you sometimes wish that you could use LINQ Select for a single object?
// for instance, if you wanted to convert that dictionary to a List of Tuples, you'd do
var tuples = dict.Select (kvp => new Tuple<int, String> (kvp.Key, kvp.Value);
// That's the idea for the .To extension method:
var tuple = dict.First ().To (kvp => new Tuple<int, String> (kvp.Key, kvp.Value);
// The .To method saves you from having to use an intermediate variable like this:
var kvp2 = dict.First ();
var tuple2 = new Tuple<int, String> (kvp2.Key, kvp2.Value);
// or calling a Dictionary twice like this:
var tuple3 = new Tuple<int, String> (dict.First ().Key, dict.First ().Value);
}
}
namespace Com.PhilChuang.Utils
{
public static class NgExtensions
{
public static TFinal To<TObject, TFinal> (this TObject self, Func<TObject, TFinal> converter)
{
return converter (self);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment