Generate class from a LINQ projection
using System; using System.Linq; using Microsoft.CSharp; using System.CodeDom; public static class QueryExtensions { public static string GetClassDefinition<T>(this IQueryable<T> query, string className) { var type = typeof(T); var sb = new StringBuilder(); sb.AppendLine(string.Format("public class {0}", className)); sb.AppendLine("{"); using (var provider = new CSharpCodeProvider()) { foreach ( var prop in type.GetProperties()) { var typeRef = new CodeTypeReference(prop.PropertyType); var propertyTypeName = provider.GetTypeOutput(typeRef); if ( !propertyTypeName.StartsWith("<>")) { propertyTypeName = propertyTypeName.Replace("System.Nullable<", String.Empty) .Replace(">","?") .Replace("System.", String.Empty); sb.AppendLine(string.Format("\tpublic {0} {1} {{get; set;}}", propertyTypeName, prop.Name)); } } ...