在选择查询中扩展现有(匿名)类型 [英] Extend an existing (anonymous) type in a select query
问题描述
在使用LinqPad时,我有一个Select x, Extra=f(y)
查询,我想在其中返回x
的所有属性(和字段),并返回与Extra
相同的级别,而不是分别作为x
和Extra
属性(或字段).
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).
可以做到吗?
即我想要Select x.p1, x.p2, Extra=f(y)
而不用输入太多.
I.e. I want Select x.p1, x.p2, Extra=f(y)
without having to type that much.
请注意,x
的类型实际上可能是匿名的,也可能不是匿名的,只是有点不透明或太大而无法手动复制.由VB.NET隐式键入和C#显式new {}
产生的类型是匿名的.
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.
推荐答案
Jon Skeet已经在此处否定回答了这个问题. (但这个问题不是重复的,因为这是特例).
Jon Skeet has already answered this question negatively here (but that question is not a duplicate because it's a special case).
作为解决方法,这里的My Extensions
至少列出了准备粘贴回Select
查询中的属性和字段.
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)):"";
}
您可能很幸运,只能够说出Select x.AllProperties("x") Take 1
,但是当您需要避免Linq-to-SQL成为障碍时,您需要添加更多内容:(from ... Select x).First().AllProperties("x")
,如果需要,还可以添加更多的选项获取属性和字段(就像我发现的那样,使用LinqPad生成的实体).
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).
这些将产生像"x.p1, x.p2"
这样的字符串,可以将其粘贴回原始的Select
查询中.
These will produce a string like "x.p1, x.p2"
that can be pasted back into the original Select
query.
这篇关于在选择查询中扩展现有(匿名)类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!