问题
While working with LinqPad I have a Select x, Extra=f(y)
query where I'd like to return all the properties (and fields) of x
at the same level as Extra
, rather than as separate x
and Extra
properties (or fields).
Can this be done?
I.e. I want Select x.p1, x.p2, Extra=f(y)
without having to type that much.
Note the type of x
may or may not actually be anonymous, just somewhat opaque or just too big to copy out manually. The type resulting from the VB.NET implicit typing and the C# explicit new {}
is anonymous.
回答1:
Jon Skeet has already answered this question negatively here (but that question is not a duplicate because it's a special case).
As a workaround here are My Extensions
to at least list the properties and fields ready to be pasted back into the Select
query.
// Properties so you can "extend" anonymous types
public static string AllProperties<T>(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 types
public static string AllFields<T>(this T obj, string VarName)
{
var fs=typeof(T).GetFields();
return fs.Any()?(VarName + "." + string.Join(", " + VarName + ".", from f in fs select f.Name)):"";
}
You may be lucky enough to just be able to say Select x.AllProperties("x") Take 1
but when you need to avoid Linq-to-SQL getting in the way you need to add more: (from ... Select x).First().AllProperties("x")
, with even more hoops if you need to get both properties and fields (as I found you do with the entities generated by LinqPad).
These will produce a string like "x.p1, x.p2"
that can be pasted back into the original Select
query.
来源:https://stackoverflow.com/questions/28937186/extend-an-existing-anonymous-type-in-a-select-query