Feature Request - Snippet to create anonymous object with corresponding properties of another object
Often I find myself writing queries of tables that have many columns but would want to remove a few columns from the results. So I would build up an anonymous object with all the properties I would want to include. This can be tedious, especially when dealing with many columns to keep. It would be nice to have a snippet that could automatically generate an anonymous object expression with all the corresponding properties of another object, preferably in definition order. Then I could just remove the columns I don't want. A workaround to this would be to start a query on a table (right clicking on it) and choose the
from/where/select new { <all columns> }
option and copy that but it gets old real fast. The `
shortcut helps but it's still a very manual process and you lose the definition order.
// LINQPad should be able to generate this for me
new
{
obj.Property1,
obj.Property2,
obj.Property3,
obj.Property4,
obj.Property5,
obj.Property6,
obj.Property7,
...
obj.PropertyN,
}
Perhaps in auto complete, when typing in 'obj.', there would be snippet called 'newanon' or something that would generate the expression.
Comments
// Properties so you can "extend" anonymous selects
public static string AllProperties(this T obj, string VarName)
{
var ps = typeof(T).GetProperties();
return ps.Any() ? (VarName + "." + string.Join(", " + VarName + ".", from p in ps select p.Name)) : "";
}
// Fields so you can "extend" anonymous selects
public static string AllFields(this T obj, string VarName)
{
var fs = typeof(T).GetFields();
return fs.Any() ? (VarName + "." + string.Join(", " + VarName + ".", from f in fs select f.Name)) : "";
}
// Properties so you can "extend" anonymous types
public static string AllPropertiesVb(this T obj, string VarName)
{
var ps = typeof(T).GetProperties();
return string.Join(", ", from p in ps select "." + p.Name + " = " + VarName + "." + p.Name);
}
// Fields so you can "extend" anonymous types
public static string AllFieldsVb(this T obj, string VarName)
{
var fs = typeof(T).GetFields();
return string.Join(", ", from f in fs select "." + f.Name + " = " + VarName + "." + f.Name);
}
// Properties so you can "extend" anonymous types
public static string AllPropertiesCs(this T obj, string VarName)
{
var ps = typeof(T).GetProperties();
return string.Join(", ", from p in ps select p.Name + " = " + VarName + "." + p.Name);
}
// Fields so you can "extend" anonymous types
public static string AllFieldsCs(this T obj, string VarName)
{
var fs = typeof(T).GetFields();
return string.Join(", ", from f in fs select f.Name + " = " + VarName + "." + f.Name);
}